排序演算法 冒泡 插入 歸併 快排

2021-07-13 21:22:06 字數 1875 閱讀 1805

整理了一下幾種常見的排序演算法,包括冒泡、插入、歸併、快排。還有另外幾種待整理:堆排序、希爾排序、桶排序

直接上**:

#include#include//#include using namespace std;

void swap(int* a, int* b)

//最簡單的氣泡排序,時間複雜度o(n*n)

void bubblesort(int a, int length)

}}//插入排序,最壞時間複雜度o(n*n)

void insertsort(int a, int length)

}//歸併排序,時間複雜度o(nlogn)

void mergearray(int a, int first, int mid, int last, int temp)

while(i<=m)

temp[k++] = a[i++];

while(j<=n)

temp[k++] = a[j++];

for(i=0; i > 1;

mergesort(a, first, mid, temp);

mergesort(a, mid+1, last, temp);

mergearray(a, first, mid, last, temp);

}}void mergesort(int a, int length)

//快速排序,平均複雜度為o(nlogn)

int randominrange(int min, int max) //產生隨機數

int partition(int a, int length, int start, int end)

}++small;

swap(&a[small],&a[end]);

return small;

}void quicksort(int a, int length, int start, int end)

int main()

; int *temp1 = a;

int *temp2 = a;

int *te*** = a;

int temp4 = ;

int n = 10;

//測試氣泡排序

bubblesort(temp1,10);

cout << "bubblesort result:";

for(int i = 0; i<10; i++)

cout << temp1[i] << " " ;

cout << endl;

//測試插入排序

insertsort(temp2,10);

cout << "insertsort result:";

for(int i = 0; i<10; i++)

cout << temp2[i] << " " ;

cout << endl;

//測試歸併排序

mergesort(te***,10);

cout << "mergesort result:";

for(int i = 0; i<10; i++)

cout << te***[i] << " " ;

cout << endl;

//測試快速排序

quicksort(temp4,8,0,7);

cout << "quicksort result:";

for(int i = 0; i<8; i++)

cout << temp4[i] << " " ;

cout << endl;

}

執行結果:

排序演算法 插入 選擇 冒泡 快排 歸併

可以找一些帖子理解下幾類排序演算法或者聽下陳越姥姥在mooc上的資料結構 選擇類排序 交換類排序 歸併排序 基數排序 拓撲排序 從待排序的n個記錄中的第二個記錄開始,依次與前面的記錄比較並尋找插入的位置,每次外迴圈結束後,將當前的數插入到合適的位置。void sort insert int a,in...

排序 冒泡,快排,歸併。

1 冒泡 就是每次相鄰的比較,較大的移到後面,一次後就移動最大的到最後面了。include void maopao int a,int len void main int len sizeof a sizeof a 0 maopao a,len for int x1 0 x12 快速排序,用遞迴來理...

冒泡,快排,插入,希爾,選擇,歸併演算法

演算法,根據資料的樣子,進行做計算。爭取在固有資料的基礎上,達到計算次數 記憶體占用最少的運算方式。現將集中演算法歸納如下 演算法名稱 演算法概要 冒泡挨個拿陣列的元素和後面的做比較,發現大小不對,則交換位置,這樣導致按照座標向後運算,座標資料是一定有序的,相對後面最大或最小 快排拿乙個陣列,向前查...