-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathQuickSort.java
More file actions
72 lines (62 loc) · 1.85 KB
/
Copy pathQuickSort.java
File metadata and controls
72 lines (62 loc) · 1.85 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
import java.util.Random;
/**
* Created by dhe on 24/12/14.
*/
public class QuickSort {
private static void quickSort(int [] array){
quickSortAlgo(array,0,array.length-1);
}
private static void quickSortAlgo(int[] array,int start,int end){
if(start < end){
int x = partitionRand(array,start,end);
quickSortAlgo(array, start, x - 1);
quickSortAlgo(array, x + 1, end);
}
}
private static int partition(int[] array, int start,int end){
// last element is pivot
int pivotData = array[end];
int index = start;
int temp;
for(int x = start;x<=end-1;x++){
if(array[x] < pivotData){
temp = array[x];
array[x] = array[index];
array[index] = temp;
index++;
}
}
array[end] = array[index];
array[index]= pivotData;
return index;
}
private static int partitionRand(int[] array, int start,int end){
Random r = new Random();
int R = r.nextInt(end-start) + start;
// last element is pivot
int temp;
temp = array[R];
array[R] = array[end];
array[end] = temp;
int pivotData = array[end];
int index = start;
for(int x = start;x<=end-1;x++){
if(array[x] < pivotData){
temp = array[x];
array[x] = array[index];
array[index] = temp;
index++;
}
}
array[end] = array[index];
array[index]= pivotData;
return index;
}
public static void main(String[] args){
int[] arr = {3,7,8,5,2,1,9,5,4};//{1,2,4,3,5,6,8,7,9,10,34};
quickSort(arr);
for(int g =0;g<arr.length;g++){
System.out.println(arr[g]+" ");
}
}
}