少年阿賓

          那些青春的歲月

            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 閱讀(606) 評論(0)  編輯  收藏 所屬分類: algorithm
          主站蜘蛛池模板: 锦州市| 新绛县| 澎湖县| 汉川市| 台江县| 宁陵县| 体育| 永安市| 浑源县| 牡丹江市| 丹江口市| 深水埗区| 苏尼特左旗| 仲巴县| 周至县| 科尔| 合作市| 波密县| 石林| 凯里市| 博湖县| 蓝田县| 武汉市| 台州市| 唐山市| 石渠县| 清丰县| 忻州市| 凤庆县| 雅江县| 金坛市| 新民市| 雷州市| 翁牛特旗| 梓潼县| 太谷县| 磐石市| 明溪县| 内黄县| 凤冈县| 广汉市|