forked from AdarshAddee/Hacktoberfest2022_for_Beginers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSort.java
51 lines (46 loc) 路 1.51 KB
/
QuickSort.java
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
//Github Username: Udyansingh
import java.util.Arrays;
import java.util.Scanner;
public class QuickSort {
public static int partition(int[] arr, int si, int ei) {
int pid, piv = arr[si], count = 0, i = si;
for (i = si + 1; i <= ei; i++) {
if (arr[i] <= piv) {
count++;
}
}
pid = count + si;
arr[si] = (arr[pid] + arr[si]) - (arr[pid] = arr[si]);
while (si < pid && ei > pid) {
if (arr[si] < piv) {
si++;
} else if (arr[ei] > piv) {
ei--;
} else {
arr[si] = (arr[ei] + arr[si]) - (arr[ei--] = arr[si++]);
}
}
return pid;
}
public static void quickSort(int[] arr, int si, int ei) {
if (si < ei) {
int p = partition(arr, si, ei);
quickSort(arr, si, p - 1);
quickSort(arr, p + 1, ei);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in).useDelimiter(",");
System.out.println("Hint: Enter Array -> 1,2,3,4,5,6 ");
System.out.print("Enter Array -> ");
String input = sc.nextLine();
String[] split = input.split(",");
int[] arr = new int[split.length];
for (int i = 0; i < split.length; i++) {
arr[i] = Integer.parseInt(split[i]);
}
quickSort(arr, 0, arr.length - 1);
System.out.println("Sorted Array -> " + Arrays.toString(arr));
sc.close();
}
}