少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks
          package com.abin.lee.algorithm.merge;
          import java.util.Arrays;
          /**
           * 歸并排序
           */
          public class MergeSort {
          public static void main(String[] args) {
          int[] input = {2,7,3,9,1,6,0,5,4,8};
          MergeSort.sort(input, 0, input.length-1);
          System.out.println("input="+Arrays.toString(input));
          }
          //首先分而自治
          /** 
               * 歸并排序 
               * 簡介:將兩個(或兩個以上)有序表合并成一個新的有序表 即把待排序序列分為若干個子序列,每個子序列是有序的。然后再把有序子序列合并為整體有序序列 
               * 時間復雜度為O(nlogn) 
               * 穩定排序方式 
               * @param nums 待排序數組 
               * @return 輸出有序數組 
               */  
          public static int[] sort(int[] input,int low,int high){
          int middle = (low+high)/2;
          if(low<high){
          //左邊
          sort(input,low,middle);
          //右邊
          sort(input,middle+1,high);
          //左右歸并
          merge(input,low,high,middle);
          }
          return input;
          }
          public static void merge(int[] input,int low,int high,int middle){
          int[] temp = new int[high-low+1];
          int i = low;//左指針
          int j = middle+1;//右指針
          int k=0;
          // 把較小的數先移到新數組中  
          while(i<=middle&&j<=high){
          if(input[i]<input[j]){
          temp[k++] = input[i++];
          }else{
          temp[k++] = input[j++];
          }
          }
          // 把左邊剩余的數移入數組  
          while(i<=middle){
          temp[k++] = input[i++];
          }
          // 把右邊邊剩余的數移入數組  
          while(j<=high){
          temp[k++] = input[j++];
          }
          // 把新數組中的數覆蓋input數組  
          for(int m=0;m<temp.length;m++){
          input[m+low] = temp[m];
          }
          }
          }
          posted on 2014-10-17 18:31 abin 閱讀(614) 評論(0)  編輯  收藏 所屬分類: algorithm
          主站蜘蛛池模板: 沙湾县| 板桥市| 田林县| 吉林市| 时尚| 灌阳县| 临沧市| 安庆市| 嘉鱼县| 广东省| 富源县| 革吉县| 留坝县| 宜良县| 澄迈县| 广平县| 施甸县| 江川县| 辉县市| 闵行区| 都安| 吕梁市| 高邑县| 公安县| 卢湾区| 景泰县| 武强县| 桂林市| 大石桥市| 黄陵县| 正定县| 余姚市| 丹棱县| 石景山区| 石门县| 罗甸县| 甘肃省| 襄汾县| 平乡县| 临西县| 科技|