-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
58 lines (51 loc) · 1.26 KB
/
Copy pathQuickSort.java
File metadata and controls
58 lines (51 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package algorithm.sorting;
import java.util.Scanner;
/**
* Quick Sort Algorithm
*/
public class QuickSort {
static void printArray(int[] arr) {
for (int i: arr) {
System.out.println(i);
}
}
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();
}
Solution.quickSort(arr, 0, n-1);
printArray(arr);
T--;
}
}
}
class Solution {
static void quickSort(int arr[], int lo, int hi) {
if (lo < hi) {
int m = partition(arr, lo, hi);
quickSort(arr, lo, m-1);
quickSort(arr, m+1, hi);
}
}
static int partition(int arr[], int p, int q) {
int i = p;
int pivot = arr[p];
for (int j = p+1; j<=q; j++) {
if (arr[j]< pivot) {
i++;
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
int tmp = arr[i];
arr[i] = arr[p];
arr[p] = tmp;
return i;
}
}