思想:
使用双指针,将数组从中间分开,递归排序,然后归并。
1.确定分界点
2.递归
3.归并
代码如下:
package cn.liyi.day02;
public class Demo787 {
public static int[] p = {2, 5, 7, 8, 4};
public static int[] temp = new int[5];
public static void main(String[] args) {
mergeSort(p, 0, 4);
for (int i = 0; i < 5; i++) {
System.out.println(p[i]);
}
}
public static void mergeSort(int[] p, int l, int r) {
if (l >= r)
return;
int mid = l + r >> 1;
mergeSort(p, l, mid);
mergeSort(p, mid + 1, r);
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r) {
if (p[i] <= p[j])
temp[k++] = p[i++];
else
temp[k++] = p[j++];
}
while (i <= mid)
temp[k++] = p[i++];
while (j <= r)
temp[k++] = p[j++];
for(i = l, j = 0; i <= r; i++, j++){
p[i] =temp[j];
}
}
}