首页 > 代码库 > 归并排序(升序)

归并排序(升序)

1、算法思

将若干个有序的序列进行两两合并,知道全部记录归并到一个序列。具体过程:将n个记录的待排序序列看成n个子序列,然后把他们两两归并,接着把长度为2的n/2个子序列再次归并,重复上述过程,直到有序为止。

2、算法实现

 

package test;public class MergeSort {          public static void main(String[] args) {          int[] n ={1,3,6,2,9,6,8,7};        mergesort(n,0,n.length-1);        for (int i : n) {            System.out.print(i+"\t");        }    }          public static int[] mergesort(int[] nums, int low, int high) {          int mid = (low + high) / 2;          if (low < high) {              mergesort(nums, low, mid);              mergesort(nums, mid + 1, high);              merge(nums, low, mid, high);          }          return nums;      }        public static void merge(int[] nums, int low, int mid, int high) {          int[] temp = new int[high - low + 1];          int i = low;        int j = mid + 1;        int k = 0;            while (i <= mid && j <= high) {              if (nums[i] < nums[j]) {                  temp[k++] = nums[i++];              } else {                  temp[k++] = nums[j++];              }          }            while (i <= mid) {              temp[k++] = nums[i++];          }            while (j <= high) {              temp[k++] = nums[j++];          }            for (int k2 = 0; k2 < temp.length; k2++) {              nums[k2 + low] = temp[k2];          }      }          }  

 

归并排序(升序)