Download presentation
Presentation is loading. Please wait.
Published byLillian Gibson Modified over 9 years ago
1
Quick Sorting -Ed. 2. and 3.: Chapter 10 -Ed. 4.: Chapter 11
2
Quick Sort
8
pivot 17 pivot 63 pivot 96 pivot 50 pivot 31
17
The running time of quick sort is proportional to the square of n, the size of the sequence: O(n 2 ). Average running time: O(nlogn). In practice, the quick sort works better than the merge sort.
18
Lab 3: import java.lang.*; public class QuickSorter { public static void quickSort (Integer[] S, Comparator c) { if (S.length < 2) return; // the array is already sorted in this case quickSortStep(S, c, 0, S.length-1); // recursive sort method } private static void quickSortStep (Object[] S, Comparator c, int leftBound, int rightBound ) { if (leftBound >= rightBound) return; // the indices have crossed Object temp; // temp object used for swapping Object pivot = S[rightBound]; int leftIndex = leftBound; // will scan rightward int rightIndex = rightBound-1; // will scan leftward while (leftIndex <= rightIndex) { // scan right until larger than the pivot while ( (leftIndex <= rightIndex) && (c.compare(S[leftIndex], pivot)<=0) ) leftIndex++;
19
// scan leftward to find an element smaller than the pivot while ( (rightIndex >= leftIndex) && (c.compare(S[rightIndex], pivot)>=0)) rightIndex--; if (leftIndex < rightIndex) { // both elements were found temp = S[rightIndex]; S[rightIndex] = S[leftIndex]; // swap these elements S[leftIndex] = temp; } }// the loop continues until the indices cross temp = S[rightBound]; // swap pivot with the element at leftIndex S[rightBound] = S[leftIndex]; S[leftIndex] = temp; // the pivot is now at leftIndex, so recurse quickSortStep(S, c, leftBound, leftIndex-1); quickSortStep(S, c, leftIndex+1, rightBound); }
20
public static void main (String[] args) { int k = 0; Integer[] nums = new Integer[10]; System.out.println("Quick sorting:" + "\n"); System.out.println("Input sequence:" + "\n"); //Create an array to hold numbers for(int i = 0; i < nums.length; i++) {k = (int) (Math.random()*100); //Generate random numbers nums[i] = new Integer(k); System.out.print(k + " "); } System.out.println();
21
Comparator c = new Comparator(); quickSort(nums, c); //Sort them System.out.println("Result:" + "\n"); for (int j = 0; j < nums.length; j++) //Print them out System.out.print(nums[j].intValue() + " "); System.out.println(); }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.