算法思想是将混乱的序列不断细分为子序列,最终子序列只剩下一个元素,对应取得相邻的两个子序列,创建一个临时数组,大小为两个子序列长度之和,用来存放两个子序列的值,存放的规则是遍历完至少一个子序列,每次在两个子序列中各取一个元素,将较小的元素存放在临时数组的前面,随后被存放元素的序列指针向后移动一位继续比较,直到有一个子序列完全遍历。没有完全遍历的序列剩下的元素直接加入临时数组中,最后将临时数组中的元素数值对应赋予原序列,完成一次归并。新归并的序列再与相邻的序列进行同样操作,一直到整个序列全部归并,排序结束
。
/**
*
* @author think
* 归并排序
* 时间复杂度o(n*logn)
*/
public class MergeSort {
public static void Merge(int[]a,int low,int mid,int high)
{
int[]temp = new int[high-low+1];//开辟临时数组,用来存储两个子序列归并后的所有元素
int s0 = low;//左边子序列的起始元素脚标
int s1 = mid+1;//右边子序列的起始元素脚标
int k = 0;//temp数组起始元素脚标
while(s0 <= mid && s1 <= high)//比较两个子序列中的元素,将较小的元素放在temp数组左侧
{
if(a[s0] < a[s1])
{
temp[k++] = a[s0++];
}else
{
temp[k++] = a[s1++];
}
}
/**
* 接下来两个循环的作用是将剩余的元素直接加在temp数组后面,因为连个子序列可能元素不一样多,只会执行一个循环
*/
while(s0 <= mid)
{
temp[k++] = a[s0++];
}
while(s1 <= high)
{
temp[k++] = a[s1++];
}
//将temp中的元素对应赋予原数组
for(int i=0;i<temp.length;i++)
{
a[low+i] = temp[i];
}
}
public static void mergeSort(int[]a,int low,int high)
{
if(low >= high)//递归终止条件
return;
int mid = (low + high)/2;
mergeSort(a,low,mid);//细分左边子序列
mergeSort(a,mid+1,high);//细分右边子序列
Merge(a,low,mid,high);//向上归并
}
public static void main(String[] args) {
int[] array=new int[]{1,2,3,30,7,8,44,10,19,16};
mergeSort(array,0,array.length-1);
for(int i=0;i<array.length;i++)
{
System.out.print(array[i]+" ");
}
}
}
。
本文详细介绍了一种高效的排序算法——归并排序。通过不断细分序列直至每个子序列仅包含一个元素,然后逐步归并相邻子序列的方式实现排序。文章提供了归并排序的具体实现代码,并解释了其时间复杂度为O(n*logn)。
714

被折叠的 条评论
为什么被折叠?



