歸併排序的實現

2021-06-16 11:23:12 字數 3073 閱讀 7455

最近工作中要用到排序,當然要選擇o(nlgn)時間複雜度的演算法,還要求是穩定的,週末就溫習了一下排序演算法,歸併排序剛好能滿足。自己也想練練手,就先實現了簡單的對遞迴版本,之後實現了非遞迴的版本。它的空間複雜度為o(n)。  因為遞迴版本會使用函式堆疊,深度受到棧記憶體的限制,所以資料量不能太大,需要注意下。

//【歸併排序--遞迴版本】

#include #include #include #include #include void swap(int *a, int *b)

void merge(int a, int m, int n)

else

}if (i < m)

else }

void mergesort(int a, int n)

int m = n/2;

mergesort(a, m);

mergesort(a + m, n - m);

merge(a, m, n);

}void setranddata(int a, int n)

}int main()

printf("\n");

clock_t t0 = clock();

mergesort(a, n);

clock_t t1 = clock();

printf("take time %d ms\n", t1 - t0);

for (int i = n/2; i < n && i < (n/2 + 200); i++)

system("pause");

return 0;

}

//【歸併排序--非遞迴版本】

#include #include #include #include #include inline int min(int a, int b)

void setranddata(int a, int n)

}void mergesort(int a, int n)

else

}if (i < end1)

else

//assert(i == end1 && j == end2 && t == end2);

i = t;

} len = min(n, len * 2);

memcpy(a, b, sizeof(int) * n);

} free(b);

}int main()

printf("\n");

clock_t t0 = clock();

mergesort(a, n);

clock_t t1 = clock();

printf("take time %d ms\n", t1 - t0);

for (int i = n/2; i < n && i < (n/2 + 100); i++)

system("pause");

return 0;

}

【歸併排序-使用模板】

mergesort.h

#ifndef __mergesort_h

#define __mergesort_h

namespace mynamespace

template void arraycopy(t *a, const t *b, int n)

inline int minindex(int a, int b)

template int mergesort(t a, int n, comparer comparer)

if (i < end1)

else

//assert(i == end1 && j == end2 && t == end2);

i = t;

}len = minindex(n, len * 2);

arraycopy(a, b, n);

} delete b;

b = null;

return 0;

} template int mergesort(t a, int n) };

#endif //__mergesort_h

main.cpp

#include #include #include #include #include "mergesort.h"

using namespace std;

int mycomparer(const int *a, const int *b)

int mycomparer2(const void *a, const void *b)

struct s

bool operator< (const s &o) };

int main()

, ,

};int a = ;

//mynamespace::mergesort(a, 5, (mynamespace::comparer)mycomparer);

mynamespace::mergesort(a, 5, mycomparer2);

printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);

// //a[1] = 100;

//mynamespace::mergesort(a, 5);

//printf("%d %d %d %d %d\n", a[0], a[1], a[2], a[3], a[4]);

mynamespace::mergesort(ss, 3);

printf("%d,%s %d,%s\n", ss[0].a, ss[0].str.c_str(), ss[1].a, ss[1].str.c_str());

system("pause");

return 0;

}

輸出

2 3 7 8 9

1,hi 2,ok

請按任意鍵繼續. . .

歸併排序實現

1,我認為歸併排序是分治思想的運用,先是把要排序的數列分成兩半,分別對這兩半進行歸併排序,一步步分下去,當分到規模為1時,開始合併兩個已經有序的陣列。2,主要的 是兩個已經有序的陣列的合併,其中涉及的有空間申請的問題和哨兵的使用。具體看 這是初寫的 存在的問題有每次迭代都申請了空間且沒釋放,而且沒有...

歸併排序實現

看到個帖子寫的歸併排序,記錄一下,特別是對鍊錶的使用。歸併的排序分為三步走 1 分割,2 遞迴,3 合併。陣列歸併排序 歸併排序三步走 1 分割子問題 2 遞迴 3 合併子問題。include stdafx.h includeusing namespace std void mergearray i...

歸併排序實現

歸併排序是建立在歸併操作上的一種有效的排序演算法。該演算法是採用分治法 divide and conquer 的乙個非常典型的應用。首先考慮下如何將將二個有序數列合併。這個非常簡單,只要從比較二個數列的第乙個數,誰小就先取誰,取了後就在對應數列中刪除這個數。然後再進行比較,如果有數列為空,那直接將另...