-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathquick_sort.java
More file actions
59 lines (51 loc) · 1.5 KB
/
quick_sort.java
File metadata and controls
59 lines (51 loc) · 1.5 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
59
package com.company;
import java.util.Scanner;
public class tc_quick_sort {
public static void quickSort(int[] arr, int lo, int hi) {
if(lo>hi){
return;
}
int pivot=arr[hi];
int pi= partition(arr,pivot,lo,hi);
quickSort(arr,lo,pi-1);
quickSort(arr,pi+1,hi);
}
public static int partition(int[] arr, int pivot, int lo, int hi) {
System.out.println("pivot -> " + pivot);
int i = lo, j = lo;
while (i <= hi) {
if (arr[i] <= pivot) {
swap(arr, i, j);
i++;
j++;
} else {
i++;
}
}
System.out.println("pivot index -> " + (j - 1));
return (j - 1);
}
// used for swapping ith and jth elements of array
public static void swap(int[] arr, int i, int j) {
System.out.println("Swapping " + arr[i] + " and " + arr[j]);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void print(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
public static void main(String[] args) throws Exception {
Scanner scn = new Scanner(System.in);
int n = scn.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scn.nextInt();
}
quickSort(arr, 0, arr.length - 1);
print(arr);
}
}