-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d7c0c1f
commit f40f631
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} |