Slippery Rock University | Dr. Deborah Whitfield | Go Browns! |
Sorting
Bubble Sort
int i, j; for (i=nElems-1; i > 0; i--) //all elems (exc 1st) for (j=0; j<i; j++) // all unsorted elem pairs if (a[j] > a[j+1]) swap(j, j+1);
int i, j; for (i=nElems-1; i > 0; i--) //N-1 passes for (j=0; j<i; j++) // N-1 + N-2 + ... + 2 + 1= N(N-1)/2 if (a[j] > a[j+1]) swap(j, j+1);Average Case:
Selection Sort
int i, j, minIndx; for (i=0; i < nElems-1; i++) { minIndx = i; for (j=i+1; j<nElems; j++) if (a[j] < a[minIndx]) minIndx = j; swap(i, minIndx); }
for (i=0; i < nElems-1; i++) { // N-1 passes minIndx = i; for (j=i+1; j<nElems; j++) // N-1 + N-2 + ... +1 if (a[j] < a[minIndx]) // = N(N-1)/2 minIndx = j; swap(i, minIndx); // N-1 }
Insertion Sort
int i, j; for (i=1; i< nElems; i++){ long temp = a[i]; j = i; while (j>0 && a[j-1]>temp){ a[j] = a[j-1]; j--; } a[j] = temp; }
for (i=1; i< nElems; i++){ // N-1 times long temp = a[i]; j = i; while (j>0 && a[j-1]>temp){ // 1,2,... N-1 (max) a[j] = a[j-1]; // = N(N-1)/2 (max) j--; // = N(N-1)/4 (avg-rand) } a[j] = temp; }
Wrap Up
if (!swapped) break; swapped = false;
Algorithm | Average | Best | Worst |
---|---|---|---|
Bubble
|
O(N2)
|
O(N)
|
O(N2)
|
Selection | O(N2) | O(N2) | O(N2) |
Insertion
|
O(N2)
|
O(N)
|
O(N2)
|