




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An explanation of three common sorting algorithms: selection sort, bubble sort, and insertion sort. It discusses the differences between worst-case and average-case analyses, and the number of comparisons and swaps required for each algorithm. The document also includes code snippets for selection sort and bubble sort.
Typology: Study notes
1 / 8
This page cannot be seen from the preview
Don't miss anything!





Divides the array into two parts: already sorted, andnot yet sorted. On each pass, finds thesmallest of the unsorted elements, and swap it intoits correct place, thereby increasing the number ofsorted elements by one.
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] SORTED [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
values [ 0 ] [ 1 ] [ 2 ] [ 3 ] [ 4 ]
4 compares for values[0] 3 compares for values[1] 2 compares for values[2] 1 compare for values[3] = 4 + 3 + 2 + 1
void SelectionSort (int values[], int numValues) //// Post:into ascendingSorts array order values[0 by key.. numValues-1 ] {int endIndex = numValues - 1 ; forSwap (int (values, current=0;current<endIndex;current++) current, MinIndex(values,current,endIndex)); }
void{ BubbleSort(int values[], int numValues) intwhile current (current = 0; < numValues - 1) {BubbleUp(values, current, numValues-1); }current++; }
void BubbleUp(intint values[],startIndex, int endIndex) //// Post:order Adjacent have been pairs switched that arebetween out of //// values[startIndex]..values[endIndex]beginning at values[endIndex]. {for (int index = endIndex; indexif (values[index] > startIndex; < index--)values[index-1]) } Swap(values,^ index,^ index-1);