Sorting Algorithms Flashcards
A sorting algorithm is ______________ if its sorts by comparing the items
Comparison based sorting
Bubble sort Best, Average, and Worst Case
O(n^2)
Selection Sort Best, Average, and Worst Case
O(n^2)
Heapsort Best, Average, and Worst Case
O(n log n)
divides the array to sorted and unsorted sections, and keeps on inserting elements to the sorted section from the unsorted part
Insertion Sort
An algorithm that doesn’t require extra proportional space.,
in-place algorithm (eg. Insertion Sort)
divide and conquer sorting algorithms
Merge Sort & Quick Sort
Insertion Sort Pseudo code
insertionsort(int a[], int n){
int i,j;
for(i=1;i<n;i++)
for(j=i: j>0; j–)
if(a[j-1] > a[j])
swap(&a[j-1],&a[j]_)
else
break;
}
Merge Sort Pseudo codeO(n log n)
mergesort(int a[], int
lower, int upper){
int mid;
if(upper-lower>0){
mid = (lower + upper)/2;
mergesort(a,lower,mid);
mergesort(a,mid+1,upper);
merge(a, lower,mid,upper);
Merge sort runs in ____________ time.
O(n log n)
T or F:
Merge sort sorts in-place.
False. Merge sort uses extra memory
QuickSort Pseudo code
QUICKSORT(A,start,pivot):
if start < pivot:
q = PARTITION(A,start,pivot)
QUICKSORT(A,start,q-1)
QUICKSORT(A,q+1,pivot)
PARTITION(A,start,pivot):
x = A[pivot]
i = start-1
for j = start to pivot-1:
if A[j] <= x:
i = i+1
swap A[i] with A[j]
swap A[i+1] with A[PIVOT]
return i+1
Quicksort runs in ______ time in the worst-case
O(n^2)
Quicksort runs in the ____________ time for best and average cases.
O(n log n)
T or F
Quicksort sorts in-place
T