归并排序

来源:互联网 发布:nginx域名重定向404 编辑:程序博客网 时间:2024/06/06 02:50

刚刚写了一篇关于快速排序的,趁热打铁索性写一个归并排序吧。其实归并排序和快速排序类似,先写递归式,再写合并方法。都是用了这种从外往里写的写法。

        1 递推式

         public static void mergeSort(int[] a,int left,int right){

                     int middle = (left + right)/2;

                     if(left<right){

                     mergeSort(a,left,middle);

                     mergeSort(a,middle+1,right);

                     merge(a,left,middle,right);

                    }

        }

       2 public static void merge(int[] a,int left,int middle,int right){

                    int[] temp = new int[right-left+1];

                    int i = left;

                    int j = middle +1;

                   int k = 0;

         while(i<=middle&&j<=right){

                   if(a[i]<a[j]){

                   temp[k++] = a[i];

                   i++;

                  }else{

                             temp[k++] = a[j];

                             j++;

                   }

                  }

                 while(i<=middle){

                             temp[k++] = a[i++];

                 }

               while(j<=right){

                           temp[k++] = a[j++];

                 }

              for(int m = 0;m<temp.length;m++){

                          a[m] = temp[m];

             }

          }

         主要是理解了思想再写,不然会显得很难。其实快速排序和归并排序都是很简单的。
1 0
原创粉丝点击