归并排序

来源:互联网 发布:imovie的windows版 编辑:程序博客网 时间:2024/06/01 10:37
/** * 归并排序比较麻烦一点,需要将数组进行分割,然后再排序,再把排序好的分割数组一一合并,因此叫做归并。 * 网上有很形象的图像说明,大家可以去搜搜看看,用文字不好描述 * @author 王嘉锐 * */public class GuiBingSort {//在这里是用来合并的public static void mergeSort(int[] source, int start1, int end1, int start2, int end2){int i = start1;//这个只是在本方法的最后一步有用到,是将起始位置保存起来。用来给原数组赋值用的。int[] temp = new int[end2 - start1 + 1]; //新建一个空的临时数组,用来保存排好的数组元素int k = 0;//排序while(start1 <= end1 && start2 <= end2){if(source[start1] < source[start2]){temp[k++] = source[start1++];} else{temp[k++] = source[start2++];}}while(start1 <= end1){temp[k++] = source[start1++];}while(start2 <= end2){temp[k++] = source[start2++];}//把已经排好的序列赋值给原来的数组k = i;for(int element : temp){source[k] = element;k++;}}//在这里进行了递归,对数组进行了分割,并调用前面的方法,进行了排序和合并。public static void sortReal(int[] source, int start, int end){if(start < end){int mid = (start + end) / 2;sortReal(source, start, mid);sortReal(source, mid + 1, end);mergeSort(source, start, mid, mid+1, end);}}//这里我只是为主方法里书写方便,专门写了个传递参数的过度方法,只是传个参数而已public static void sort(int[] source){int start = 0;int end = source.length - 1;sortReal(source, start, end);}public static void main(String[] args) {int[] a = {321,545,213,98,1,34,5,21};sort(a);for(int i = 0; i < a.length; i++){System.out.println(a[i]);}}}

原创粉丝点击