归并排序

来源:互联网 发布:58同城网招聘淘宝客服 编辑:程序博客网 时间:2024/05/22 03:36
package com.sort;public class MergeSort {public static void main(String[] args) {int[] a=new int[]{-6,5,4,3,-2,1};mergeSort(a,0,a.length-1);for(int array:a){System.out.println(array);}}public static void mergeSort(int[]a ,int start, int end){if(start >= end){return;}int mid = (start+end)/2;mergeSort(a, start, mid);mergeSort(a, mid+1, end);merge(a, start, mid, end);}private static void merge(int[] a, int first, int mid, int last) {int[] temp = new int[(last-first+1)];    int i = first;int j = mid + 1;      int m = mid;int n = last;      int k = 0;      while (i <= m && j <= n)      {          if (a[i] <= a[j])              temp[k++] = a[i++];          else              temp[k++] = a[j++];      }      while (i <= m)          temp[k++] = a[i++];            while (j <= n)          temp[k++] = a[j++];      for (i = 0; i < k; i++)          a[first + i] = temp[i];  }}

0 0
原创粉丝点击