合并排序算法(java实现)

public class MergeSort2 {
	public static void merge(int a[], int p, int q, int r){
		int l1 = q-p+1;
		int l2 = r-q;
		int[] array1 = new int[l1 + 1];
		int[] array2 = new int[l2 + 1];
		for(int i = 0; i<l1; i++){
			array1[i] = a[p+i];
		}
		for(int i = 0; i<l2; i++){
			array2[i]= a[q+1+i]; 
		}
		//将数组中的最后一个元素设置为最大值,这样就不必担心会有数据元素剩余,
		//同时k的取值范围决定了无穷值不会被添加到原数据中
		array1[l1] = Integer.MAX_VALUE;
		array2[l2] = Integer.MAX_VALUE;
		int i = 0;
		int j = 0;
		for(int k = p; k<=r; k++){
			if(array1[i] <= array2[j] ){
				a[p++]= array1[i];
				i++;
			}else{
				a[p++]= array2[j];
				j++;
			}
		}
	}
	public static void mergeSort(int a[], int low, int high){
		if(low == high){
			return;
		}else{
			int poi = (low + high)/2;
			mergeSort(a, low, poi);
			mergeSort(a, poi + 1, high);
			merge(a, low, poi, high);
		}
	}
	public static void main(String[] args) {
		int[] array = {1,3,6,4,6,4,8,3,8,3,0};
		mergeSort(array, 0, array.length - 1);
		for(int i = 0; i<array.length; i++){
			System.out.print(array[i] + "  ");
		}
	}
}

你可能感兴趣的:(合并排序算法(java实现))