diff --git a/Quick sort b/Quick sort new file mode 100644 index 0000000..ff46f66 --- /dev/null +++ b/Quick sort @@ -0,0 +1,67 @@ +//Quick sort + +import java.util.*; + +class Sorting { + static void printArray(int arr[]) { + int n = arr.length; + + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + int T = sc.nextInt(); + + while(T > 0) { + int n = sc.nextInt(); + int arr[] = new int[n]; + + for(int i = 0; i < n; i++) + arr[i] = sc.nextInt(); + + new Solution().quickSort(arr,0,n-1); + printArray(arr); + T--; + } + } +} + +class Solution { + static void quickSort(int arr[], int low, int high) { + if(low < high) { + int pIdx = partition(arr, low, high); + quickSort(arr, low, pIdx - 1); + quickSort(arr, pIdx + 1, high); + } + } + static int partition(int arr[], int low, int high) { + int pivot = arr[low]; + int i = low, j = high; + + while(i < j) { + while(arr[i] <= pivot && i <= high - 1) { + i++; + } + + while(arr[j] > pivot && j >= low + 1) { + j--; + } + + if(i < j) { + int temp = arr[i]; + arr[i] = arr[j]; + arr[j] = temp; + } + } + + int temp = arr[low]; + arr[low] = arr[j]; + arr[j] = temp; + + return j; + } +}