归并排序(merge sort)

归并排序,算法复杂度为O(nlogn),属于快速排序范畴。

算法简介
归并算法的思想是divide and conquer,分治法。将一个大的问题分解为若干的小问题,将小问题各个击破和,在对小问题进行合并。divide and conquer在计算机世界里是一种很常见的方法,大到系统设计小到一个算法的设计都可能用到它。
归并算法是这样的:
divide:我们把待排序的算法分成两个子数组,再把每个子数组分成两个子数组,再把。。。当子数组中只有一个数据时,那么这个子数据当然就是已排序好了的数组(sorted),下面要进行的操作就是:
conquer:当我们要把两个已排序的子数组合并成一个大数组时,我们可以这样:i,j分别指向连个数组开始的地方,比较A[i]与B[j]的大小,将小的放到大数组C[K]中,然后更新指针。比如(A[i] < B[j], 那么C[k] = A[i], i++,k++);
在计算机的世界里,收获都是靠一定的付出换回来的。当归并排序将算法复杂度降到了O(nlogn)时,其空间复杂度可以说在某种程度上增加了。以为我们需要使用一个临时数组来储存数据。
需要注意的问题
1,不一定要缩减到子数组的length == 1,当子数据的长度较小的时候,我们可以用简单排序算放将其排序。
2,因为用用到临时数组,如果我们在conquer函数内申请一个局部变量的临时数组,由于conquer函数会多次调用,临时数组也就会多次初始化,浪费资源。

代码
package sorting;

public class Data {
	
	/**
	 * generate an unsorted array of length n
	 * @param n length
	 * @param max the maximum integer element of this array
	 * @return an unsorted array consists of elements range from 1 to max
	 */
	public static int[] getArray(int n, int max){
		int[] result = new int[n];
		for(int i =0; i < n; i++){
			result[i] = (int)(Math.random() * max + 1);
		}
		return result;
	}
	/**
	 * print the array
	 * @param arg array
	 */
	public static void printArray(int[] arg){
		StringBuffer temp = new StringBuffer();
		for(int i = 0; i < arg.length; i++){
			temp.append(arg[i] + "\t");
		}
		System.out.println(temp);
	}
}

package sorting;

public class MergeSort {
	private int[] temp;

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MergeSort ms = new MergeSort();
		int[] data = Data.getArray(10, 100);
		System.out.print("Source data:\t");
		Data.printArray(data);
		ms.applyTempArray(data.length);
		ms.mergeSort(data,0,data.length - 1);
		System.out.print("Sorted data:\t");
		Data.printArray(data);

	}
	
	public void applyTempArray(int n){
		this.temp = new int[n];
	}
	/**
	 * before calling this function fist time, user must call applyTemp to apply for a temporary array
	 * @param array
	 * @param begin
	 * @param end
	 */
	public void mergeSort(int[] array, int begin, int end){
		if(begin < end){// the condition when the recursion comes to an end
			//divide
			int mid = (begin + end) /2;
			mergeSort(array,begin, mid);
			mergeSort(array,mid + 1, end);
			//conquer
			merge(array,begin,mid,end);
		}
	}
	public void merge(int[] array, int begin, int mid, int end){
		int begin_1 = begin;
		int end_1 = mid;
		int begin_2 = mid + 1;
		int end_2 = end;
		int length = end - begin + 1;
		int index = 0;
		while(begin_1 <= end_1 && begin_2 <= end_2){// make sure that the two sub array will not out of bounds
			if(array[begin_2] < array[begin_1]){
				this.temp[index] = array[begin_2];
				index++;
				begin_2++;
			}
			else{
				this.temp[index] = array[begin_1];
				index++;
				begin_1++;
			}
		}
		//make sure the rest of one sub array are copied to temp
		if(begin_1 != (end_1 + 1)){//the first sub array has remaining elements, pay attention to: end_1 + 1
			for(;index < length; index++,begin_1++){
				this.temp[index] = array[begin_1];
			}
			
		}else{
			for(;index < length; index++,begin_2++){
				this.temp[index] = array[begin_2];
			}
		}
		// copy temp to array
		for(index = 0; index < length; index++){
			array[begin + index] = this.temp[index];
		}
	}
}


### 归并排序的实现原理 归并排序是一种基于分治法(Divide and Conquer)的有效排序算法。其核心思想是通过将待排序数组分割为更小的部分,分别对这些部分进行排序后再将其合并成为一个整体有序的结果[^1]。 具体来说,归并排序的过程可以分为以下几个方面: #### 1. **分解** 整个数据集被递归地划分为较小的子集合,直到每个子集合仅包含单个元素为止。因为单一元素本身已经是有序的,所以这一步骤完成了基础单元的创建[^2]。 #### 2. **合并** 当所有的子集合都已经被拆解到最小单位之后,开始逐步地把它们两两合并起来,在每次合并的过程中都会确保新形成的组合也是按照顺序排列好的。这种“归并”的过程会一直持续下去,直至最终形成一个完整的、完全有序的数据列表[^3]。 以下是归并排序的核心伪代码表示: ```python def merge_sort(arr): if len(arr) <= 1: return arr mid = len(arr) // 2 left_half = merge_sort(arr[:mid]) right_half = merge_sort(arr[mid:]) return merge(left_half, right_half) def merge(left, right): sorted_array = [] i = j = 0 while i < len(left) and j < len(right): if left[i] < right[j]: sorted_array.append(left[i]) i += 1 else: sorted_array.append(right[j]) j += 1 sorted_array.extend(left[i:]) sorted_array.extend(right[j:]) return sorted_array ``` 这段代码展示了如何使用 Python 来实现归并排序的功能。其中 `merge` 函数负责执行实际的合并操作,而 `merge_sort` 则控制着递归调用以及何时停止进一步划分输入数组。 ### 时间复杂度分析 由于每一次都将当前序列分成两半处理,并且每一层都需要遍历全部 n 项来进行比较和移动,因此总的运行时间为 O(n log n)。 ### 稳定性特点 值得注意的是,归并排序属于稳定性的排序方式之一,这意味着即使存在相等的关键字记录也不会改变彼此原有的次序关系。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值