-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSort.java
More file actions
109 lines (97 loc) · 2.87 KB
/
Copy pathSort.java
File metadata and controls
109 lines (97 loc) · 2.87 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
package Algorithm;
public class Sort {
static int times=0;
public static void swap(int[] a, int i, int j){
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
public static int erFenSearch(int [] a, int target){
int low=0;
int high=a.length-1;
while(high>=low){
int middle=(low+high)/2;
if(a[middle]==target) return middle;
if(a[middle]>target) high=middle-1;
else low=middle+1;
}
return -1;
}
public static void quickSort(int[] a,int low,int high){
if(low>=high) return;
int index=partition(a,low,high);
quickSort(a,low,index-1);
quickSort(a,index+1,high);
}
public static int partition(int[] a,int low,int high){
int flag=a[low];//取出标杆元素
int i=low,j=high+1;
while(j>i){
while(flag>a[++i]){
if(i==high) break;
}
while(flag<a[--j]){
if(j==low) break;
}
if(i>j) break;
swap(a,i,j);
}
swap(a,low,j);
System.out.println("第"+ ++times+"次快速排序结果");
for(int m=0; m<a.length; m++){
System.out.print(a[m]+" ");
}
System.out.println();
return j;
}
public static void bubbleSort(int []a,int low,int high){
if(low>=high) return;
for(int i=low; i<high; i++){
for(int j=0; j<high; j++){
if(a[j]>a[j+1]) swap(a,j,j+1);
}
}
}
public static void selectSort(int[] a,int low,int high){
if(low>=high) return;
for(int i=low; i<high; i++){
int min=a[i];
int minIndex=i;
for(int j=i+1; j<=high; j++){
if(a[j]<min) {
min=a[j];
minIndex=j;
}
}
swap(a,minIndex,i);
}
}
public static void insertSort(int[] a,int low,int high){
for(int i=low+1; i<=high; i++){
for(int j=i; j>low; j--){
if(a[j]<a[j-1]) swap(a,j-1,j);
}
}
}
public static void heapSort(int []a){
for(int i=a.length/2-1; i>=0; i--){
//从第一个非叶子结点从下至上,从右至左调整结构
adjustHeap(a,i,a.length);
}
for(int j=a.length-1; j>0; j--){
swap(a,0,j);//把大的放后面,实现排序
adjustHeap(a,0,j);
}
}
public static void adjustHeap(int []a,int start,int length){
int temp=a[start];//取出当前元素
for(int k=2*start+1; k<length; k=k*2+1){
if(k+1<length && a[k+1]>a[k]) k+=1;//右儿子大
if(a[k]>temp) {
a[start]=a[k];
start=k;
} else break;
}
a[start]=temp;
}
}