-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSortRecursion.java
More file actions
59 lines (55 loc) · 1.18 KB
/
QuickSortRecursion.java
File metadata and controls
59 lines (55 loc) · 1.18 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
public class QuickSortRecursion {
private int[] array;
public QuickSortRecursion(int[] array){
this.array = array;
}
public void sort(){
quickSort(0, array.length-1);
printArray();
}
private void quickSort(int begin, int end){
if(begin<end){
int pos = partition(begin, end);
quickSort(begin, pos-1);
quickSort(pos+1, end);
}
}
private int partition(int begin,int end){
int c = array[end];
int i = begin-1;
for(int j=begin;j<end;j++){
if(array[j]<=c){
i++;
swap(i, j);
}
}
swap(i+1, end);
return i+1;
}
private void swap(int i, int j){
if(i!=j){
int c = array[i];
array[i] = array[j];
array[j] = c;
}
}
private void printArray(){
for(int i=0;i<array.length;i++){
System.out.print(array[i]+" ");
}
}
public static void main(String[] args ) throws Exception{
int[] array = randomizeArray(10);
QuickSortRecursion quickSorter = new QuickSortRecursion(array);
quickSorter.sort();
}
private static int[] randomizeArray(int length){
int[] array = new int[length];
for(int i=0;i<length;i++){
array[i] = (int) (Math.random()*10);
System.out.print(array[i]+" ");
}
System.out.println();
return array;
}
}