-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort_Partition.java
More file actions
109 lines (99 loc) · 3.19 KB
/
Copy pathQuickSort_Partition.java
File metadata and controls
109 lines (99 loc) · 3.19 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package sort;
import java.util.Arrays;
/**
* Partition procedure of QuickSort.
* @author xiuzhu
* 151118
*/
public class QuickSort_Partition {
/**
* 1、先从数列中取出一个数作为基准数,基数为r
* 2、i从左到右依次存放比r下的数
*
* @author 周何圳 2018年05月30日 新建
*/
//Partition in CLRS
public int partition(int a[], int start, int end){
int index = -1;
if(a == null || a.length <= 1)
return index;
int i = -1, r = a[end];
for (int j = 0; j < a.length; j++) {
if(a[j] <= r){
int temp = a[j];
a[j] = a[++i];
a[i] = temp;
index = i;
}
}
return index;
}
//problem 7.1-4,partition in DESC.
public void partition_desc(int a[], int start, int end){
if(a == null || a.length <= 1)
return;
int i = -1, r = a[end];
for (int j = 0; j < a.length; j++) {
if(a[j] >= r){
int temp = a[j];
a[j] = a[++i];
a[i] = temp;
}
}
}
//traditional partition
public int partition_traditional(int a[], int start, int end){
if(a == null || a.length <= 1)
return -1;
int r = a[end];
int i = 0, j = end;
while(i < j){
while(a[i] <= r && i < j)
i++;
while(a[j] >= r && i < j)
j--;
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
if(i == j){
int temp = a[i];
a[i] = a[end];
a[end] = temp;
}
return i;
}
//call all 3 methods above. --- Just to facility test.
public void call_all_partition(int a[], int start, int end){
System.out.println("Original Array: " + Arrays.toString(a));
int a1[] = a.clone();
int a2[] = a.clone();
partition(a, start, end);
partition_traditional(a1, start, end);
partition_desc(a2, start, end);
System.out.println("Partition in CLRS: " + Arrays.toString(a));
System.out.println("Partition in traditional: " + Arrays.toString(a1));
System.out.println("Partition in CLRS desc: " + Arrays.toString(a2));
System.out.println("----------------------------------");
}
//test
public static void main(String[] args) {
QuickSort_Partition p = new QuickSort_Partition();
System.out.println("----------------------------------");
int a0[] = {10,4,20,5};
int a1[] = {1};
int a2[] = {2,1};
int a3[] = {1 ,2, 3};
int a4[] = {3, 2, 1};
int a5[] = {3, 1, 2};
int a6[] = {13,19,9,5,12,8,7,4,21,2,6,11};
/*p.call_all_partition(a0, 0, a0.length - 1);
p.call_all_partition(a1, 0, a1.length - 1);
p.call_all_partition(a2, 0, a2.length - 1);
p.call_all_partition(a3, 0, a3.length - 1);
p.call_all_partition(a4, 0, a4.length - 1);
p.call_all_partition(a5, 0, a5.length - 1);
p.call_all_partition(a6, 0, a6.length - 1);*/
System.out.println(p.partition(a6,0,a6.length-1));
}
}