1. 题目描述
使用归并排序排序数组
2. 考察知识点
归并排序
3. 思路
- 归并排序排序的基本思路为将一个序列分为两半,对每一半进行归并排序,将得到两个有序的序列,然后将两个有序序列归并为一个序列即可,此处运动了递归的思想,接下来需要写两个函数,分别为主函数,归并函数。
- 主函数sort(),完成数组划分工作,并实现递归功能。值得注意的是,直到划分为每个数组的值为单个数字时(有序),才结束。
public static int[] sort(int[] a,int low,int high){
int mid = (low+high)/2;
if(low<high){
sort(a,low,mid);//归并排序前半段
sort(a,mid+1,high);//归并排序后半段
merge(a,low,mid,high);//归并操作
}
return a;
}
- 归并函数merge(),实现归并功能。
(1) 由于两个数组是有序的,对比两个数组第一个元素,把较小的数移到新数组中,就可以得到一个有序的数组
(2)最后检测左数组和右数组是否还有元素,有的话移入新数组。
(3)最后新数组覆盖原数组
4. 代码(Java)
//主函数
public static int[] sort(int[] a,int low,int high){
int mid = (low+high)/2;
if(low<high){
sort(a,low,mid);//归并排序前半段
sort(a,mid+1,high);//归并排序后半段
merge(a,low,mid,high);//归并操作
}
return a;
}
//归并操作函数
public static void merge(int[] a, int low, int mid, int high) {
int[] temp = new int[high-low+1];
int i= low;
int j = mid+1;
int k=0;
// 对比两个数组第一个元素,把较小的数移到新数组中
while(i<=mid && j<=high){
if(a[i]<a[j]){
temp[k++] = a[i++];
}else{
temp[k++] = a[j++];
}
}
// 把左边剩余的数移入数组
while(i<=mid){
temp[k++] = a[i++];
}
// 把右边边剩余的数移入数组
while(j<=high){
temp[k++] = a[j++];
}
// 把新数组中的数覆盖nums数组
for(int x=0;x<temp.length;x++){
a[x+low] = temp[x];
}
}
5. 时间及空间复杂度
时间复杂度:O(nlog2n),执行次数为要归并的两个子序列中关键字个数之和。
空间复杂度:O(n),因为需要转存整个待排序序列。
6. 知识积累
暂无