|
| 1 | +/* |
| 2 | + * To change this license header, choose License Headers in Project Properties. |
| 3 | + * To change this template file, choose Tools | Templates |
| 4 | + * and open the template in the editor. |
| 5 | + */ |
| 6 | +package learning; |
| 7 | + |
| 8 | +/** |
| 9 | + * |
| 10 | + * @author akshatsharma |
| 11 | + */ |
| 12 | +public class QuickSort { |
| 13 | + |
| 14 | + void swap(int[] arr, int from, int to) { |
| 15 | + int temp = arr[from]; |
| 16 | + arr[from] = arr[to]; |
| 17 | + arr[to] = temp; |
| 18 | + } |
| 19 | + |
| 20 | + |
| 21 | + int partition(int[] arr, int p, int r) { |
| 22 | + System.out.println("Partitioning Array from index p : " + p + " r : " + r); |
| 23 | + int x = arr[r]; |
| 24 | + int i = p - 1; |
| 25 | + for(int j = p; j <= (r - 1); j++) { |
| 26 | + if(arr[j] < x) { |
| 27 | + i++; |
| 28 | + swap(arr, i, j); |
| 29 | + } |
| 30 | + } |
| 31 | + i++; |
| 32 | + swap(arr, i, r); |
| 33 | + System.out.println("Pivot Element at i : " + i + " = " + arr[i]); |
| 34 | + printArray(arr); |
| 35 | + return i; |
| 36 | + } |
| 37 | + |
| 38 | + void quickSort(int[] arr, int p, int r) { |
| 39 | + if(p < r) { |
| 40 | + System.out.println("Quick Sort Called with index p : " + p + " r : " + r); |
| 41 | + int q = partition(arr, p, r); |
| 42 | + quickSort(arr, p, q - 1); |
| 43 | + quickSort(arr, q + 1, r); |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + void printArray (int[] array) { |
| 48 | + System.out.println(); |
| 49 | + for (int i = 0; i < array.length; i++) { |
| 50 | + System.out.print(array[i] + " "); |
| 51 | + } |
| 52 | + System.out.println(); |
| 53 | + } |
| 54 | + |
| 55 | + void performFunctionality() { |
| 56 | + int[] arr = {2,8,7,1,3,5,6,4}; |
| 57 | + System.out.println("Array before Sorting"); |
| 58 | + printArray(arr); |
| 59 | + quickSort(arr, 0, arr.length - 1); |
| 60 | + System.out.println("After Sorting Array"); |
| 61 | + printArray(arr); |
| 62 | + } |
| 63 | + |
| 64 | +} |
0 commit comments