Day1:归并排序

归并排序(MERGE-SORT)是利用归并的思想实现的排序方法,该算法采用经典的分治(divide-and-conquer)策略(分治法将问题(divide)成一些小的问题然后递归求解,而治(conquer)的阶段则将分的阶段得到的各答案"修补"在一起,即分而治之)。

代码实现:


public class bbb2 {
	public static int[] sort(int array[],int low,int high)
	{
		int mid=(high+low)/2;
		if(low<high)
		{
			sort(array,low,mid);
			sort(array,mid+1,high);
			merge(array,low,mid,high);
		}
		return array;
	}
	
	private static void merge(int[] array, int low, int mid, int high) {
		int temp[]=new int [high-low+1];/*为什么加1?因为等下参数输入的时候high是length-1(因为比如lenth=10的时候末尾位置是9),而这里是新建一个数组,长度应该和array相等,所以应该是high-low+1而不是high-low*/
		//设置临时变量保存分割成的两端数组的头标
		int i=low;
		int j=mid+1;
		int k=0;//这个是给temp用的
		//从小到大排序
		while(i<=mid&&j<=high)
		{
			if(array[i]<array[j])
				temp[k++]=array[i++];
			else
				temp[k++]=array[j++];
		}
		//把array[i]里面剩下的加入temp
		while(i<=mid)
		{
			temp[k++]=array[i++];
		}
		//把array[j]里面剩下的加入temp
		while(j<=high)
		{
			temp[k++]=array[j++];
		}
		//把temp里面的重新导入array
		for(int m=0;m<array.length;m++)
		{
			array[m+low]=temp[m];//为什么是array[m+low]而不是array[m]?因为对于sort(array,mid+1,high)来说,他的low是mid+1,如果用array[m]的话,那这半边就加入不了了。
		}		
	}
	public static void main(String[] args) {
		int[] nums = { 2, 7, 8, 3, 1, 6, 9, 0, 5, 4 }; 
		bbb.sort(nums, 0, nums.length-1);
		System.out.println(Arrays.toString(nums));
	}
}

运行结果:

猜你喜欢

转载自blog.csdn.net/qq_40311377/article/details/83504010
今日推荐