-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.java
More file actions
75 lines (65 loc) · 1.8 KB
/
QuickSort.java
File metadata and controls
75 lines (65 loc) · 1.8 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//QuickSort takes O(N^2)time complexity and O(logN) space complexity in worst case but we can prevent that by shuffling the array.
//In average case it takes O(N*logN)
import java.util.Random;
public class QuickSort {
private int partition(int[] a, int lo, int hi) {
int i=lo, j=hi+1;
while(true) {
//Finding items on left to swap
while(less(a[++i],a[lo])) {
if(i==hi) break;
}
//Finding items on right to swap
while(less(a[lo], a[--j])) {
if(j==lo) break;
}
if(i>=j) break; //Checking if pointers i and j cross
exch(a,i,j); //Swapping
}
exch(a,lo,j); //Swapping items with partitioning item
return j; //Returning the index of the item now know to be in place(i.e. mid item)
}
//Comparing Function
public boolean less(int v, int w) {
return v<w;
}
//Swapping Function
private static void exch(int[] a, int i, int j) {
int swap = a[i];
a[i] = a[j];
a[j] = swap;
}
//Sorting Recursively
public int[] sort(int[] a) {
shuffleArray(a);
sort(a,0,a.length-1);
return a;
}
private int[] sort(int[] a, int lo, int hi) {
if(hi<=lo) return a;
int j = partition(a, lo, hi);
sort(a,lo,j-1);
sort(a,j+1,hi);
return a;
}
//Shuffling the array for performance guarantee
public static void shuffleArray(int[] b) {
Random rnd = new Random();
for (int i = b.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
int temp = b[index];
b[index] = b[i];
b[i] = temp;
}
}
public static void main(String[] args) {
int[] array = {7,10,5,3,8,4,2,9,6};
QuickSort qs = new QuickSort();
int sortedArray[] = qs.sort(array);
for(int i=0;i<array.length;i++) {
System.out.print(sortedArray[i]);
System.out.print(" ");
}
}
}