Steps
- Choose any element of the array to be the pivot.
- Divide all other elements (except the pivot) into two partitions which is all elements less than the pivot must be in the first partition and all elements greater than the pivot must be in the second partition.
- Use recursion to sort both partitions.
- Join the first sorted partition, the pivot, and the second sorted partition.
Below are the pseudocode on how quick sort works
function quicksort(array) if length(array) > 1 pivot := select any element of array left := first index of array right := last index of array while left ≤ right while array[left] < pivot left := left + 1 while array[right] > pivot right := right - 1 if left ≤ right swap array[left] with array[right] left := left + 1 right := right - 1 quicksort(array from first index to right) quicksort(array from left to last index)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | import java.util.*; import java.lang.*; public class QuickSort { public static void main(String[] args) { int[] x = { 99, 22, 14, 37, 13, 87, 100 }; System.out.println(Arrays.toString(x)); int low = 0; int high = x.length - 1; quickSort(x, low, high); System.out.println(Arrays.toString(x)); } public static void quickSort(int[] arr, int low, int high) { if (arr == null || arr.length == 0) return; if (low >= high) return; // pick the pivot int middle = low + (high - low) / 2; int pivot = arr[middle]; // make left < pivot and right > pivot int i = low, j = high; while (i <= j) { while (arr[i] < pivot) { i++; } while (arr[j] > pivot) { j--; } if (i <= j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; i++; j--; } } // recursively sort two sub parts if (low < j) quickSort(arr, low, j); if (high > i) quickSort(arr, i, high); } } |
No comments:
Post a Comment