归并排序java实现

来源:互联网 发布:mac怎么升级系统版本 编辑:程序博客网 时间:2024/06/04 23:30

归并排序:所有排序均在合并阶段进行。

package MyPackage;import java.util.Arrays;public class KthSmall {public static void main(String[] args) {int[] tar=new int[]{4,5,1,3,6,6,13,154,6,34,6134,123,613,13};sort(tar);System.out.println(Arrays.toString(tar) );}public static void sort(int[] input){mergeSort(input, new int[input.length], 0, input.length-1);}public static void mergeSort(int[] input,int[] helper,int start,int stop){if(start<stop){int mid=start+((stop-start)>>1);mergeSort(input,helper,start,mid);mergeSort(input,helper, mid+1, stop);merge(input,helper,start,mid,stop);}}public static void merge(int[] input,int[] helper,int start,int mid,int stop){for(int i=start;i<=stop;i++){helper[i]=input[i];}int i=start,j=mid+1,k=start;while(i<=mid&&j<=stop){if(helper[i]<helper[j]){input[k++]=helper[i++];}else {input[k++]=helper[j++];}}while(i<=mid){input[k++]=helper[i++];}}}


下边是归并的另一种写法:

public class Mergesort {  private int[] numbers;  private int[] helper;  private int number;  public void sort(int[] values) {    this.numbers = values;    number = values.length;    this.helper = new int[number];    mergesort(0, number - 1);  }  private void mergesort(int low, int high) {    // check if low is smaller then high, if not then the array is sorted    if (low < high) {      // Get the index of the element which is in the middle      int middle = low + (high - low) / 2;      // Sort the left side of the array      mergesort(low, middle);      // Sort the right side of the array      mergesort(middle + 1, high);      // Combine them both      merge(low, middle, high);    }  }  private void merge(int low, int middle, int high) {    // Copy both parts into the helper array    for (int i = low; i <= high; i++) {      helper[i] = numbers[i];    }    int i = low;    int j = middle + 1;    int k = low;    // Copy the smallest values from either the left or the right side back    // to the original array    while (i <= middle && j <= high) {      if (helper[i] <= helper[j]) {        numbers[k] = helper[i];        i++;      } else {        numbers[k] = helper[j];        j++;      }      k++;    }    // Copy the rest of the left side of the array into the target array    while (i <= middle) {      numbers[k] = helper[i];      k++;      i++;    }  }} 


0 0
原创粉丝点击