-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquickSort.java
62 lines (50 loc) · 1.56 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
54
55
56
57
58
59
60
61
62
import java.io.*;
import java.util.*;
public class quickSort {
// function to do the partition of an array
public static int partition(int[] arr, int l, int h){
int pivot = arr[l];
int i = l;
for(int j=l+1; j<=h; j++){
if(arr[j] <= pivot){
i = i + 1;
// swap(arr[i], arr[j])
int tem = arr[i];
arr[i] = arr[j];
arr[j] = tem;
}
}
// swap (arr[l], arr[i])
// to get the correct position of the pivot element
int tem = arr[l];
arr[l] = arr[i];
arr[i] = tem;
return i;
}
// function of the quicksort algorithm
public static void quickSort(int[] arr, int l, int h){
if(l < h){
// 1. Divide the array into two subproblems
int m = partition(arr, l, h);
// 2. Conquer the subproblems via the recursion
quickSort(arr, l, m-1);
quickSort(arr, m+1, h);
}
}
// function to display the array
public static void printArr(int[] arr, int n){
for(int i=0; i<n; i++){
System.out.print(arr[i]+" ");
}
System.out.println(" ");
}
public static void main(String[] args){
int[] arr = {50, 30, 70, 90, 10, 34, 89, 98, 13};
int n = arr.length;
System.out.println("Array before sorting is: ");
printArr(arr, n);
quickSort(arr, 0, n-1);
System.out.println("Array after sorting is: ");
printArr(arr, n);
}
}