-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathQuickSort.java
53 lines (43 loc) · 1.11 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
52
53
import java.util.Arrays;
import java.util.Scanner;
class QuickSort {
private static Scanner sc;
public static void main(String args[]) {
sc = new Scanner(System.in);
System.out.println("Enter no of terms");
int n = sc.nextInt();
System.out.println("Enter the terms");
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("The unsorted array is:");
System.out.println(Arrays.toString(arr));
sort(arr, 0, arr.length - 1);
System.out.println("The sorted array is:");
System.out.println(Arrays.toString(arr));
}
static void sort(int arr[], int start, int end) {
if (start < end) {
int pIndex = partition(arr, start, end);
sort(arr, start, pIndex - 1);
sort(arr, pIndex + 1, end);
}
}
static int partition(int arr[], int start, int end) {
int pivot = arr[end];
int pIndex = start;
for (int i = start; i < end; i++) {
if (arr[i] <= pivot) {
swap(arr, i, pIndex);
pIndex++;
}
}
swap(arr, pIndex, end);
return pIndex;
}
static void swap(int arr[], int x, int y) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}