選擇 氣泡排序法C 實現

2021-07-11 04:02:12 字數 3011 閱讀 5608

一開始把選擇排序法理解錯了。於是寫出如下**:

#include

using

namespace

std;

void comp(int *ptr1, int *ptr2)

}int main();

int *p = a;

cout

<< "排序前:"

<< endl;

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

cout

<< a[i] << " ";

cout

<< endl;

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

}cout

<< "排序後:"

<< endl;

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

cout

<< a[i] << " ";

cout

<< endl;

cout

<< "迴圈次數:"

<< cnt0 << endl;

cout

<

<< cnt << endl;

return

0;}

該**的運作如下:

比較第乙個位置與後面位置元素的大小。只要第乙個位置元素比後面位置元素大就交換它們。第乙個位置的值在動態改變。

比較第二個位置與後面位置元素的大小。只要第二個位置元素比後面位置元素大就交換它們。

依次,直到最後乙個位置,排序結束。

感覺這就是選擇和冒泡的雜交版本。

但其實真正的選擇排序應該是這樣的:

首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然後,再從剩餘未排序元素中繼續尋找最小(大)元素,然後放到已排序序列的末尾。以此類推,直到所有元素均排序完畢。 —— [ 維基百科 ]

**如下:

#include

using

namespace

std;

//選擇法

int main();

//輸出排序前序列

cout

<< "排序前:"

<< endl;

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

cout

<< a[i] << " ";

cout

<< endl;

//選擇法進行排序

cout

<< "每輪交換後序列:"

<< endl;

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

++cnt0;//迴圈次數

}a[labeli] = a[i];//將i位置的值放在最小值所在的位置上

a[i] = min;//將最小值放在i位置上

//輸出該輪交換後的序列

cout

<< "第"

<< ++cnt << "次交換後:\n";//cnt:交換次數

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

cout

<< a[se] << " ";

cout

<< endl;

}//輸出選擇排序後結果

cout

<< "排序後:"

<< endl;

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

cout

<< a[i] << " ";

cout

<< endl;

cout

<< "迴圈次數:"

<< cnt0 << endl;

cout

<< "交換次數:"

<< cnt << endl;

return

0;}

其中需要對尋找到的最小值進行下標標記。

氣泡排序演算法的運作如下:

1、比較相鄰的元素。如果第乙個比第二個大,就交換他們兩個。

2、對每一對相鄰元素作同樣的工作,從開始第一對到結尾的最後一對。這步做完後,最後的元素會是最大的數。

3、針對所有的元素重複以上的步驟,除了最後乙個。

4、持續每次對越來越少的元素重複上面的步驟,直到沒有任何一對數字需要比較。

—— [ 維基百科 ]

**如下(來自維基百科):

#include 

#include

using

namespace

std;

template

//整數或浮點數皆可使用,若要使用物件(class)時必須設定大於(>)的運運算元功能

void bubble_sort(t arr, int len)

int main() ;

int len = (int) sizeof(arr) / sizeof(*arr);

bubble_sort(arr, len);

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

cout

<< arr[i] << ' ';

cout

<< endl;

float arrf = ;

len = (int) sizeof(arrf) / sizeof(*arrf);

bubble_sort(arrf, len);

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

cout

<< arrf[i] << ' ';

return

0;}

排序相關的演算法有很多,還有演算法的評價指標。日後一點點補上。

氣泡排序法 選擇排序法

相鄰兩個數進行比較 如果前者比後者大 就把前者和後者互換 比如十個數 經過九次比較 就可以得到乙個最大的數字於排列的最末端 再經過八次比較 可以得到乙個第二大的數 依次類推 即最大的數一次一次冒泡上來。include int main printf n 資料排序 for i 0 i 9 i 列印資料...

陣列實現冒泡法和選擇法排序(C )

include include using namespace std void bubble sort int arry,int num void getarry int arry,int num void outarry int arry,int num void select sort int...

冒泡法排序C 實現

看一下 include using namespace std function count the number of count variable void printf int a,int count cout endl void bubblesort int a,int count cout...