Skip to content

Commit

Permalink
Create Quick sort
Browse files Browse the repository at this point in the history
  • Loading branch information
dishathakurata authored May 14, 2024
1 parent d7c0c1f commit f40f631
Showing 1 changed file with 67 additions and 0 deletions.
67 changes: 67 additions & 0 deletions Quick sort
Original file line number Diff line number Diff line change
@@ -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;
}
}

0 comments on commit f40f631

Please sign in to comment.