110 likes | 154 Views
Selection Sort and Quick Sort. Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in. Selection sort. class SelectionSort { public static void main (String arg[]) { int size = 20; double array[] = new double[size]; Initialize (array, size); // not shown
E N D
Selection Sort and Quick Sort Instructor: Mainak Chaudhuri mainakc@cse.iitk.ac.in
Selection sort class SelectionSort { public static void main (String arg[]) { int size = 20; double array[] = new double[size]; Initialize (array, size); // not shown PrintArray (array, size); // not shown Sort (array, size); PrintArray (array, size); // not shown }
Selection sort public static void Sort (double array[], int size) { int i, j, minIndex; for (i=0;i<=size-2;i++) { minIndex = i; for (j=i+1;j<size;j++) { if (array[j] < array[minIndex]) { minIndex = j; } } Swap (array, minIndex, i); // Invariant: array[0] to array[i] is sorted } }
Selection sort public static void Swap (double array[], int p, int q) { double temp; temp = array[p]; array[p] = array[q]; array[q] = temp; } } // end class (How many comparisons?)
Selection sort • Better than bubble sort by a constant factor • Less number of assignments • Asymptotically both are O(n2)
Quick sort • Pick a “pivot” element and put it in its place • All elements to its left are smaller and all to its right are bigger • Recursively sort the left half and the right half • Best case is O(nlogn), same as merge sort • Worst case is O(n2) • Recall that the worst case time for merge sort is O(nlogn)
Quick sort class QuickSort { public static void main (String arg[]) { int n = 20; double array[] = new double[n]; Initialize (array, n); // not shown Sort (array, 0, n-1); } // continued on next slide
Quick sort public static void Sort (double array[], int start, int end) { int pivot; if (start < end) { if (start == end-1) { if (array[start] > array[end]) { Swap (array, start, end); } } else { pivot = Partition (array, start, end); Sort (array, start, pivot-1); // left half Sort (array, pivot+1, end); // right half } } } // continued in next slide
Quick sort public static int Partition (double array[], int start, int end) { int pivot = start; int downstream = start+1; int upstream = end; while (true) { while ((downstream <= end) && (array[downstream] <= array[pivot])) { downstream++; } // continued in next slide
Quick sort while ((upstream > start) && (array[upstream] >= array[pivot])) { upstream--; } if (downstream < upstream) { Swap(array, downstream, upstream); } else { break; } } Swap (array, pivot, upstream); return upstream; } // continued in next slide
Quick sort public static void Swap (double array[], int p, int q) { double temp; temp = array[p]; array[p] = array[q]; array[q] = temp; } } // end class