首页 > 代码库 > 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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。