您的位置:首页 > 编程语言 > Java开发

java编程题:用Java实现一个归并排序算法

2017-03-29 18:28 471 查看
import java.util.Arrays;

/**
* java编程题:用Java实现一个归并排序算法
*
* 基本思想:把原始数组分成若干子数组,对每一个子数组进行排序,继续把子数组与子数组合并,合并后仍然有序,直到全部合并完,形成有序的数组。
*
*/
public class Test20 {

public static void main(String[] args) {

int a[] = { 51, 46, 20, 18, 65, 97, 82, 30, 77, 50 };
sort(a, 0, a.length - 1);
System.out.println("排序结果:" + Arrays.toString(a));

}

/**
* 分解,递归将一个数组分成2个数组
*
*/
private static void sort(int[] array, int left, int right) {
int middle = (left + right)/2;
if(left < right){
//左边数组递归分解 array[left...middle]
sort(array, left, middle);

//右边数组递归分解 array[middle+1...right]
sort(array, middle+1, right);

//二路子数组归并
merge(array, left, middle, right);
}
}

/**
* 合并数组
*
*/
private static void merge(int[] array, int left, int middle, int right) {
int[] temp = new int[right - left + 1]; //存放合并数组的新数组
int i = left; //左边数组的下标
int j = middle+1; //右边数组的下标
int k = 0; //临时用于存放合并数组的下标

while(i <= middle && j <= right){
if(array[i] < array[j]){ //左边数组的第一个元素小,放入新数组中
temp[k] = array[i];
i++;
k++;
//简化写法: temp[k++] = array[i++];
}else{ //右边数组的第一个元素小,放入新数组中
temp[k] = array[j];
j++;
k++;
//简化写法: temp[k++] = array[j++];
}
}

//左边剩余的数归并到新数组中
while(i <= middle){
temp[k] = array[i];
i++;
k++;
//简化写法:temp[k++] = array[i++];
}

//右边剩余的数归并到新数组中
while(j <= right){
temp[k] = array[j];
j++;
k++;
//简化写法:temp[k++] = array[j++];
}

//把新数组覆盖原来的数组
for (int kk = 0; kk < temp.length; kk++) {
array[kk + left] = temp[kk];
}
}

}

参考: http://blog.csdn.net/jianyuerensheng/article/details/51262984 http://www.cnblogs.com/jingmoxukong/p/4308823.html http://www.cnblogs.com/hexiaochun/archive/2012/09/04/2670070.html http://www.cnblogs.com/skywang12345/p/3602369.html#a43 http://blog.csdn.net/li_zhenxing/article/details/25183771
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐