-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathQuickSort.java
More file actions
61 lines (50 loc) · 1.26 KB
/
Copy pathQuickSort.java
File metadata and controls
61 lines (50 loc) · 1.26 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
package quickSort;
public class QuickSort {
private static <T extends Comparable<? super T>> void sortFirstMiddleLast(T[] a,int first ,int mid ,int last)
{
order(a,first,mid);
order(a,mid,last);
order(a,first,mid);
}
private static <T extends Comparable<? super T>> void order(T[] a,int i,int j)
{
if(a[i].compareTo(a[j])>0)
{
swap(a,i,j);
}
}
private static void swap(Object[] array,int i,int j)
{
Object temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static <T extends Comparable<? super T>> int partition(T[] a,int first,int last)
{
int mid = (first+last)/2;
sortFirstMiddleLast(a,first,mid,last);
swap(a,mid,last-1);
int pivotIndex = last-1;
T pivot = a[pivotIndex];
int indexFromLeft = first +1;
int indexFromRight = last - 2;
boolean done = false;
while(!done)
{
while(a[indexFromLeft].compareTo(pivot) <0)
indexFromLeft++;
while(a[indexFromRight].compareTo(pivot) >0)
indexFromRight--;
assert a[indexFromLeft].compareTo(pivot) >= 0 && a[indexFromRight].compareTo(pivot) <=0;
if(indexFromLeft < indexFromRight)
{
swap(a,indexFromLeft,indexFromRight);
indexFromLeft++;
indexFromRight--;
}else{
done = true;
}
}
return pivotIndex;
}
}