-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort_Randomized.java
More file actions
99 lines (88 loc) · 2.76 KB
/
Copy pathQuickSort_Randomized.java
File metadata and controls
99 lines (88 loc) · 2.76 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
package sort;
import java.util.Arrays;
import java.util.Random;
/**
* 7.3 快速排序的随机化版本
*
* @author 周何圳 2018年05月30日 新建
*/
public class QuickSort_Randomized {
Random r = new Random();
//Randomized Partition
public int partition_Randomized(int a[],int start,int end){
int index = -1;
if(a == null || a.length <= 1){
return index;
}
//和普通版本的区别 -- 将数组随机化
randomnizedArray(a,start,end);
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;
}
/**
* 将数组随机化,就是把end和start(包括)……end(不包括)……之间的一个数随机交换
*
* @author 周何圳 2018年05月30日 新建
*/
public void randomnizedArray(int a[], int start,int end){
if(start == end){
return;
}
// 产生一个随机的index,end>index>=start
int randamIndex = -1;
while(randamIndex < start){
randamIndex = r.nextInt(end);
}
//交换randamIndex和end元素
int temp = a[randamIndex];
a[randamIndex] = a[end];
a[end] = temp;
}
/**
* 快速排序随机版
*
* @author 周何圳 2018年05月30日 新建
*/
public void sort_Randomized(int[] a, int start, int end){
int mid = partition_Randomized(a,start,end);
if(mid + 1 < end){
sort_Randomized(a,mid + 1,end);
}
if (mid > start + 1){
sort_Randomized(a,start,mid - 1);
}
}
//test
public static void main(String[] args) {
QuickSort_Randomized s = new QuickSort_Randomized();
int a0[] = {};
int a1[] = {1};
int a2[] = {2,1};
int a3[] = {1,2, 3, 4, 5};
int a4[] = {5,4, 3, 2, 1};
int a5[] = {3, 1, 2};
int a6[] = {13,19,9,5,12,8,7,4,21,2,6,11};
s.sort_Randomized(a0, 0, a0.length - 1);
s.sort_Randomized(a1, 0, a1.length - 1);
s.sort_Randomized(a2, 0, a2.length - 1);
s.sort_Randomized(a3, 0, a3.length - 1);
s.sort_Randomized(a4, 0, a4.length - 1);
s.sort_Randomized(a5, 0, a5.length - 1);
s.sort_Randomized(a6, 0, a6.length - 1);
System.out.println(Arrays.toString(a0));
System.out.println(Arrays.toString(a1));
System.out.println(Arrays.toString(a2));
System.out.println(Arrays.toString(a3));
System.out.println(Arrays.toString(a4));
System.out.println(Arrays.toString(a5));
System.out.println(Arrays.toString(a6));
}
}