CNG213 Lecture 3 - Sorting-Searching
CNG213 Lecture 3 - Sorting-Searching
• The first three are the foundations for faster and more efficient
algorithms.
After pass 1
After pass 2
After pass 3
After pass 4
After pass 5
• The best case, the worst case, and the average case of the
selection sort algorithm are same. all of them are O(n2)
– This means that the behavior of the selection sort algorithm does not
depend on the initial organization of data.
– Since O(n2) grows so rapidly, the selection sort algorithm is appropriate only
for small n.
– Although the selection sort algorithm requires O(n 2) key comparisons, it only
requires O(n) moves.
– A selection sort could be a good choice if data moves are costly but key
comparisons are not costly (short keys, long records).
CNG 213 - Lecture 3 9/53
Insertion Sort
• Insertion sort is a simple sorting algorithm that is appropriate for
small inputs.
– Most common sorting technique used by card players.
• In each pass, the first element of the unsorted part is picked up,
transferred to the sorted sub-list, and inserted at the appropriate
place.
• A list of n elements will take at most n-1 passes to sort the data.
After pass 1
After pass 2
After pass 3
After pass 4
After pass 5
• Worst:
– Longest running time (this is the upper limit for the algorithm)
– It is guaranteed that the algorithm will not be worse than this.
• The smallest element is bubbled from the unsorted list and moved
to the sorted sub-list.
• After that, the wall moves one element ahead, increasing the
number of sorted elements and decreasing the number of
unsorted ones.
• Each time an element moves from the unsorted part to the sorted
part one sort pass is completed.
After pass 1
After pass 2
After pass 3
After pass 4
• It is a recursive algorithm.
– Divides the list into halves,
– Sort each halve separately, and
– Then merge the sorted halves into one sorted array.
• Arranging the array elements around the pivot p generates two smaller sorting
problems.
– Sort the left section of the array, and sort the right section of the array.
– When these two smaller sorting problems are solved recursively, our bigger sorting problem is solved.
21 }
22 // place pivot in proper position and mark its location
23 swap(theArray[first], theArray[lastS1]);
24 pivotIndex = lastS1;
25 } CNG 213 - Lecture 3 38/53
Quicksort Function
1 void quicksort(DataType theArray[], int first, int last) {
2 // Sorts the items in an array into ascending order.
3 // Precondition: theArray[first..last] is an array.
4 // Postcondition: theArray[first..last] is sorted.
5 // Calls: partition.
6 int pivotIndex;
7 if (first < last) {
8 // create the partition: S1, pivot, S2
9 partition(theArray, first, last, pivotIndex);
10 // sort regions S1 and S2
11 quicksort(theArray, first, pivotIndex-1);
12 quicksort(theArray, pivotIndex+1, last);
13 }
14 }
(bad,bar) (cat) (dad) (fat) (god) (him) (mad,mom) (pat) group strings by first
letter