



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




Sorting
CMPS 12B, UC Santa Cruz Sorting 3
do { done = 1; for (j = 0; j < nItems-1; j++) { if (arr[j] > arr[j+1]) { temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; done = 0; } } } while (!done);
! Keeps going as long as at least one swap was made ! How do we know it’ll eventually end?
! Large elements “bubble” to the end of the array ! Outer loop runs at most nItems- times
! OK if a few items slightly out of order
CMPS 12B, UC Santa Cruz Sorting 7
while (unsorted list not empty) { pop item off unsorted list for (cur = sorted.first; cur is not last && cur.value < item.value; cur = cur.next) { ; if (cur.value < item.value) { insert item after cur // last on list } else { insert item before cur } } for (j = 1; j < nItems; j++) { curr = arr[j]; for (k = j-1; (k>=0) && (arr[k]>curr); k--) { arr[k+1] = arr[k]; } arr[k+1] = curr; }
CMPS 12B, UC Santa Cruz Sorting 9