210 likes | 328 Views
This document explores the QuickSort algorithm, detailing its efficiency and implementation in Java. QuickSort typically exhibits an average running time of O(n log n) and performs better than MergeSort in practical applications. The implementation includes the key sorting method and recursive sorting steps in Java, allowing users to sort an array of integers efficiently. Additionally, it demonstrates how to generate a random sequence of integers and showcase the sorting results, underlining the algorithm's effectiveness.
E N D
Quick Sorting • Ed. 2. and 3.: Chapter 10 • Ed. 4.: Chapter 11
pivot 50 pivot 96 pivot 31 pivot 63 pivot 17
The running time of quick sort is proportional to the square of n, the size of the sequence: O(n2). Average running time: O(nlogn). In practice, the quick sort works better than the merge sort.
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++;
// 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); }
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();
System.out.println(); System.out.println(); 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(); } }