Skip to content

Commit bff2d39

Browse files
author
wangzheng
committed
12_sorts
1 parent 35f6a3a commit bff2d39

File tree

2 files changed

+101
-0
lines changed

2 files changed

+101
-0
lines changed

java/12_sorts/MergeSort.java

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package sorts;
2+
3+
/**
4+
* Created by wangzheng on 2018/10/16.
5+
*/
6+
public class MergeSort {
7+
8+
// 归并排序算法, a是数组,n表示数组大小
9+
public static void mergeSort(int[] a, int n) {
10+
mergeSortInternally(a, 0, n-1);
11+
}
12+
13+
// 递归调用函数
14+
private static void mergeSortInternally(int[] a, int p, int r) {
15+
// 递归终止条件
16+
if (p >= r) return;
17+
18+
// 取p到r之间的中间位置q
19+
int q = (p+r)/2;
20+
// 分治递归
21+
mergeSortInternally(a, p, q);
22+
mergeSortInternally(a, q+1, r);
23+
24+
// 将A[p...q]和A[q+1...r]合并为A[p...r]
25+
merge(a, p, q, r);
26+
}
27+
28+
private static void merge(int[] a, int p, int q, int r) {
29+
int i = p;
30+
int j = q+1;
31+
int k = 0; // 初始化变量i, j, k
32+
int[] tmp = new int[r-p+1]; // 申请一个大小跟a[p...r]一样的临时数组
33+
while (i<=q && j<=r) {
34+
if (a[i] <= a[j]) {
35+
tmp[k++] = a[i++]; // i++等于i:=i+1
36+
} else {
37+
tmp[k++] = a[j++];
38+
}
39+
}
40+
41+
// 判断哪个子数组中有剩余的数据
42+
int start = i;
43+
int end = q;
44+
if (j <= r) {
45+
start = j;
46+
end = r;
47+
}
48+
49+
// 将剩余的数据拷贝到临时数组tmp
50+
while (start <= end) {
51+
tmp[k++] = a[start++];
52+
}
53+
54+
// 将tmp中的数组拷贝回a[p...r]
55+
for (i = 0; i <= r-p; ++i) {
56+
a[p+i] = tmp[i];
57+
}
58+
}
59+
60+
}

java/12_sorts/QuickSort.java

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package sorts;
2+
3+
/**
4+
* Created by wangzheng on 2018/10/16.
5+
*/
6+
public class QuickSort {
7+
8+
// 快速排序,a是数组,n表示数组的大小
9+
public static void quickSort(int[] a, int n) {
10+
quickSortInternally(a, 0, n-1);
11+
}
12+
13+
// 快速排序递归函数,p,r为下标
14+
private static void quickSortInternally(int[] a, int p, int r) {
15+
if (p >= r) return;
16+
17+
int q = partition(a, p, r); // 获取分区点
18+
quickSortInternally(a, p, q-1);
19+
quickSortInternally(a, q+1, r);
20+
}
21+
22+
private static int partition(int[] a, int p, int r) {
23+
int pivot = a[r];
24+
int i = p;
25+
for(int j = p; j < r; ++j) {
26+
if (a[j] < pivot) {
27+
int tmp = a[i];
28+
a[i] = a[j];
29+
a[j] = tmp;
30+
++i;
31+
}
32+
}
33+
34+
int tmp = a[i];
35+
a[i] = a[r];
36+
a[r] = tmp;
37+
38+
System.out.println("i=" + i);
39+
return i;
40+
}
41+
}

0 commit comments

Comments
 (0)