少年阿賓

          那些青春的歲月

            BlogJava :: 首頁 :: 聯系 :: 聚合  :: 管理
            500 Posts :: 0 Stories :: 135 Comments :: 0 Trackbacks

          常用鏈接

          留言簿(22)

          我參與的團隊

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          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
          主站蜘蛛池模板: 甘谷县| 兖州市| 泾川县| 肥东县| 靖边县| 西安市| 宁化县| 仁布县| 海盐县| 浦北县| 惠水县| 河曲县| 广德县| 京山县| 富顺县| 湖南省| 南川市| 安远县| 寿阳县| 北辰区| 无极县| 眉山市| 定远县| 容城县| 汶川县| 宝应县| 新民市| 万宁市| 含山县| 天柱县| 绥滨县| 蓬溪县| 温宿县| 福鼎市| 柳州市| 德钦县| 台湾省| 磴口县| 泽州县| 昔阳县| 鸡泽县|