Skip to content

Commit 29a8533

Browse files
committed
add sort algorithms
1 parent 9f8a9e4 commit 29a8533

File tree

3 files changed

+59
-4
lines changed

3 files changed

+59
-4
lines changed

src/com/duweri/interview/search/BinarySearch.java

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,8 @@ public class BinarySearch {
55
/**
66
* 二分查找又称折半查找,它是一种效率较高的查找方法。 【二分查找要求】:1.必须采用顺序存储结构 2.必须按关键字大小有序排列。
77
*
8-
* @param array
9-
* 有序数组 *
10-
* @param searchKey
11-
* 查找元素 *
8+
* @param array 有序数组
9+
* @param searchKey 查找元素
1210
* @return searchKey的数组下标,没找到返回-1
1311
*/
1412
public static int binarySearch(int[] array, int searchKey) {
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.duweri.interview.sort;
2+
3+
/**
4+
* 归并排序
5+
* http://www.cnblogs.com/chengxiao/p/6194356.html
6+
*/
7+
public class MergeSort {
8+
9+
public static void sort(int[] arr) {
10+
int[] temp = new int[arr.length];//在排序前,先建好一个长度等于原数组长度的临时数组,避免递归中频繁开辟空间
11+
sort(arr, 0, arr.length - 1, temp);
12+
}
13+
14+
/**
15+
*
16+
* @param arr 待排序数组
17+
* @param left
18+
* @param right
19+
* @param temp 临时数组
20+
*/
21+
private static void sort(int[] arr, int left, int right, int[] temp) {
22+
if (left < right) {
23+
int mid = (left + right) / 2;
24+
sort(arr, left, mid, temp);//左边归并排序,使得左子序列有序
25+
sort(arr, mid + 1, right, temp);//右边归并排序,使得右子序列有序
26+
merge(arr, left, mid, right, temp);//将两个有序子数组合并操作
27+
}
28+
}
29+
30+
private static void merge(int[] arr, int left, int mid, int right, int[] temp) {
31+
int i = left;//左序列指针
32+
int j = mid + 1;//右序列指针
33+
int t = 0;//临时数组指针
34+
while (i <= mid && j <= right) {
35+
if (arr[i] <= arr[j]) {
36+
temp[t++] = arr[i++];
37+
} else {
38+
temp[t++] = arr[j++];
39+
}
40+
}
41+
while (i <= mid) {//将左边剩余元素填充进temp中
42+
temp[t++] = arr[i++];
43+
}
44+
while (j <= right) {//将右序列剩余元素填充进temp中
45+
temp[t++] = arr[j++];
46+
}
47+
t = 0;
48+
//将temp中的元素全部拷贝到原数组中
49+
while (left <= right) {
50+
arr[left++] = temp[t++];
51+
}
52+
}
53+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
package com.duweri.interview.sort;
2+
3+
public class QuickSort {
4+
}

0 commit comments

Comments
 (0)