首页 > 代码库 > Iterative (non-recursive) Merge Sort

Iterative (non-recursive) Merge Sort

An iterative way of writing merge sort:

#include <iostream>
using namespace std;

void merge(int A[], int l, int r, int e, int B[]) {
	int i = l, j = r, k = l;
	while (i<r && j<e) {
		if (A[i] > A[j]) B[k++] = A[j++];
		else B[k++] = A[i++];
	}
	while (i < r) B[k++] = A[i++];
	while (j < e) B[k++] = A[j++];
}

void mergeSort(int A[], int n) {
	int *B = new int[n];
	for (int w=1; w<n; w<<=1) {
		for (int i=0; i<n; i+=(w<<1)) {
			merge(A, i, min(i+w, n), min(i+(w<<1), n), B);
		}
		for (int i=0; i<n; ++i) A[i] = B[i];
	}
	delete[] B;
}

int main() {
	int A[5] = {5,4,3,2,1};
	mergeSort(A, 5);
	for (int i=0; i<5; ++i) cout<<A[i]<<" ";
	return 0;
}