|
| 1 | +// Java program for implementation of QuickSort |
| 2 | +class QuickSort |
| 3 | +{ |
| 4 | + /* This function takes last element as pivot, |
| 5 | + places the pivot element at its correct |
| 6 | + position in sorted array, and places all |
| 7 | + smaller (smaller than pivot) to left of |
| 8 | + pivot and all greater elements to right |
| 9 | + of pivot */ |
| 10 | + int partition(int arr[], int low, int high) |
| 11 | + { |
| 12 | + int pivot = arr[high]; |
| 13 | + int i = (low-1); // index of smaller element |
| 14 | + for (int j=low; j<high; j++) |
| 15 | + { |
| 16 | + // If current element is smaller than or |
| 17 | + // equal to pivot |
| 18 | + if (arr[j] <= pivot) |
| 19 | + { |
| 20 | + i++; |
| 21 | + |
| 22 | + // swap arr[i] and arr[j] |
| 23 | + int temp = arr[i]; |
| 24 | + arr[i] = arr[j]; |
| 25 | + arr[j] = temp; |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + // swap arr[i+1] and arr[high] (or pivot) |
| 30 | + int temp = arr[i+1]; |
| 31 | + arr[i+1] = arr[high]; |
| 32 | + arr[high] = temp; |
| 33 | + |
| 34 | + return i+1; |
| 35 | + } |
| 36 | + |
| 37 | + |
| 38 | + /* The main function that implements QuickSort() |
| 39 | + arr[] --> Array to be sorted, |
| 40 | + low --> Starting index, |
| 41 | + high --> Ending index */ |
| 42 | + void sort(int arr[], int low, int high) |
| 43 | + { |
| 44 | + if (low < high) |
| 45 | + { |
| 46 | + /* pi is partitioning index, arr[pi] is |
| 47 | + now at right place */ |
| 48 | + int pi = partition(arr, low, high); |
| 49 | + |
| 50 | + // Recursively sort elements before |
| 51 | + // partition and after partition |
| 52 | + sort(arr, low, pi-1); |
| 53 | + sort(arr, pi+1, high); |
| 54 | + } |
| 55 | + } |
| 56 | + |
| 57 | + /* A utility function to print array of size n */ |
| 58 | + static void printArray(int arr[]) |
| 59 | + { |
| 60 | + int n = arr.length; |
| 61 | + for (int i=0; i<n; ++i) |
| 62 | + System.out.print(arr[i]+" "); |
| 63 | + System.out.println(); |
| 64 | + } |
| 65 | + |
| 66 | + // Driver program |
| 67 | + public static void main(String args[]) |
| 68 | + { |
| 69 | + int arr[] = {10, 7, 8, 9, 1, 5}; |
| 70 | + int n = arr.length; |
| 71 | + |
| 72 | + QuickSort ob = new QuickSort(); |
| 73 | + ob.sort(arr, 0, n-1); |
| 74 | + |
| 75 | + System.out.println("sorted array"); |
| 76 | + printArray(arr); |
| 77 | + } |
| 78 | +} |
0 commit comments