java 归并排序实现

package com.algorithm.charactor1;

import java.util.Arrays;

public class GuiBinSort {

	public static void main(String[] args) {
		Integer [] arr = {3,5,2,1,5,6,4};
		
		Integer[] sort = sort(arr,0,arr.length-1,new Integer[arr.length]);
		
		String string = Arrays.toString(sort);
		
		System.out.println(string);
	}

	
	private static Integer[] sort(Integer[] arr, int left, int right, Integer[] temp) {
		if (left< right) {
			
			int mid = (left+right)/2; //选择对序列的分割线
			
			sort(arr, left, mid, temp);//对左边序列排序
			
			sort(arr, mid+1, right, temp);//对右边你序列排序
			
			merge(arr,left,mid,right,temp);//对递归产生的 子序列进行合并到 temp中
		}
		
		
		return arr;
		
	}


	private static void merge(Integer[] arr, int left, int mid, int right, Integer[] temp) {
		
		int i = left;//左序列的开始索引
		int j = mid+1;//右序列的开始索引
		
		int k = 0;//合并临时数组的开始索引
		
		while(i<=mid && j<=right){//左右序列上的 数字  排序到 temp上,直到左右子序列 一个循环完
			
			if (arr[i]<= arr[j]) {//说明j所在的序列的值大
				temp[k++] = arr[i++];
			}else {
				temp[k++] = arr[j++];
			}
			
		}
		
		while(i<=mid){//说明j所在序列排序完毕了
			temp[k++] = arr[i++];
		}
		
		while(j<=right){//说明i所在序列排序完毕了
			temp[k++] = arr[j++];
		}
		
		k=0;
		
		while(left<=right){//将两个子序列 归到arr数组中
			arr[left++] = temp[k++];
		}
	}
	
}

猜你喜欢

转载自blog.csdn.net/woyixinyiyi/article/details/79970094