数据结构-*-归并排序
程序员文章站
2022-05-10 15:12:13
...
package per.lihao.sort.complexsort;
import per.lihao.sort.SortSequence;
import per.lihao.sort.simplesort.BubbleSort;
/**
* 二路归并排序
* 时间复杂度为:O(nlogn)
* Author: LiHao
* Time: 2018/12/13 14:13
*/
public class MergeSort {
private static void mergeSort(int[] array,int begin,int end){
if (begin>=end)
{
return;
}
int mid = (begin+end) >> 1;
mergeSort(array,begin,mid);
mergeSort(array,mid+1,end);
merge(array,begin,mid,end);
}
private static void merge(int[] array,int begin,int mid,int end){
int[] a = new int[end-begin+1];
int i=begin,j=mid+1,k=0;
while (i<mid+1 && j<end+1){
if (array[i]<array[j]){
a[k++] = array[i++];
}else {
a[k++] = array[j++];
}
}
if (i<=mid){
for (int start = i;start<=mid;start++){
a[k++] = array[start];
}
}
if (j<=end){
for (int start = j;start<=end;start++){
a[k++] = array[start];
}
}
k = 0;
for (int start = begin;start<=end;start++){
array[start] = a[k++];
}
}
public static int[] sort(int[] array,boolean reverse){
int[] result = array.clone();
mergeSort(result,0,result.length-1);
return result;
}
public static void main(String[] args) {
SortSequence ss = new SortSequence(82,195,19,108,153,39,120,125,136,181);
ss.printMem();
System.out.println("****************************");
int[] a = MergeSort.sort(ss.getMem(),true);
BubbleSort.printArray(a);
}
}
上一篇: scrapy在pycharm环境下调试
下一篇: 归并排序模板(附求逆序对)