1、合并排序(归并排序)
(1)、基本思想
代排序元素分成大小大致相同的两个自己和,分别对两个子集合进行排序,最终将排好序的子集合合并成所要求的排好序的集合。
(2)、时间复杂度
T(n)=O(nlogn)
(3)、 算法步骤
a.将数组一分为二,分到剩下一个元素为止(递归处理)
b.将分好的数据按大小一个个排好序合并到原来的数组
c.递归结束
(4)、代码
import java.util.*;
public class MergeSort {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("please input the size of array:");
int size = input.nextInt();
System.out.println("please input the arrays:");
int[] array = new int[size];
for(int i=0; i<size; i++) {
array[i] = input.nextInt();
}
System.out.println(Arrays.toString(mergeSort(array, 0, size-1)));
input.close();
}
//先将数组一分为二,分到只有一个元素为止,所以用的是递归
public static int[] mergeSort(int array[], int left, int right) {
int mid = (left+right)/2;
if(left<right) {
//分割左边
mergeSort(array, left, mid);
//分割右边
mergeSort(array, mid+1, right);
//合并
merge(array, left, mid, right);
}
return array;
}
//合并的过程
public static void merge(int[] array, int left, int mid, int right) {
//创建一个辅助的数组
int[] temp = new int[right-left+1];
int i = left;
int j = mid+1;
int k = 0;
//将元素一个个有序地排
while(i<=mid && j<=right) {
if(array[i]<array[j]) {
temp[k++] = array[i++];
}else {
temp[k++] =array[j++];
}
}
//剩余的元素放到缓存数组的后面
while(i<=mid) {
temp[k++] = array[i++];
}
while(j<=right) {
temp[k++] = array[j++];
}
//再将原数据放回原数组
for(int index=0; index<temp.length; index++) {
array[index+left] = temp[index];
}
}
}
(5)、运行记录
参考博客:https://blog.csdn.net/qq_25827845/article/details/70994874
参考教材:计算机算法设计与分析 王晓东 著 2016