码迷,mamicode.com
首页 > 编程语言 > 详细

归并排序思想

时间:2019-12-29 20:24:57      阅读:66      评论:0      收藏:0      [点我收藏+]

标签:规模   实现   dex   sys   数据   color   移动   turn   技术   

归并排序(merge-sort)是以分治的思想,把排序的数组化分为左右两部分,比较两数组中索引所指向的元素大小,

将小的放入新的数组中,并将该索引向下移动一个位置。

实现是采用递归调用方式,把要排序的数组拆分成左右两部分直到分成单个元素(分),再分别对左右两部分元素进行排序合并(合)

再把有序的这两部分合并,该过程依次进行,最后得到有序的数组。

 

技术图片

 1 //归并排序
 2 @Test
 3 public void mergeSort(){
 4     
 5     int arr[] = {100,7,9,4,1,6,3,10,5};
 6         
 7     int[] result = sort(arr, 0, arr.length-1);
 8     
 9     for(int i=0;i<result.length;i++){
10         System.out.print(result[i] + " ");
11     }
12 }
13 
14 public int[] sort(int arr[],int startIndex, int endIndex){
15     if(startIndex >= endIndex){
16         return new int[] {arr[endIndex]};
17     }
18     int midIndex = (startIndex+endIndex)/2;
19     int[] left = sort(arr, startIndex, midIndex);
20     int[] right = sort(arr, midIndex+1, endIndex);
21     return merge(left, right);
22 }
23 
24 public int[] merge(int[] left, int[] right){
25     int L_len = left.length, R_len = right.length;
26     int i=0,j=0,k=0;
27     int[] temp = new int[L_len + R_len];
28     
29     //将左右两边的子数组中的元素进行比较
30     while(i < L_len && j < R_len){
31         if(left[i] <= right[j]){
32             temp[k++] = left[i++];
33         }else{
34             temp[k++] = right[j++];
35         }
36     }
37     
38     //将子数组中剩余的元素放入排序数组的后面,下面的两个循环只会执行一个
39     while(i < L_len){
40         temp[k++] = left[i++];
41     }
42     
43     while(j < R_len){
44         temp[k++] = right[j++];
45     }
46     
47     return temp;
48 }

归并排序将把要排序的数组从中间一分为二,分为左边和右边,然后左右分别排序,排好了之后再合并到一起,相对于冒泡、插入、选择这三种排序时间复杂度是O(n2)来说适合大规模的数据排序,它的时间复杂度是O(nlogn)。

它是稳定排序,即原来相等的元素排序后的相对位置不发生改变。

归并排序思想

标签:规模   实现   dex   sys   数据   color   移动   turn   技术   

原文地址:https://www.cnblogs.com/superwei001/p/12115953.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!