您好,登錄后才能下訂單哦!
c語言冒泡排序的方法:
先選定第一個數(shù)字為最大再對數(shù)字兩兩進行比較,得到兩者之間的最大值,依次比較。具體代碼實現(xiàn)如下:
#include <iostream> #include <time.h> using namespace std; void srandData(int *, int );//產(chǎn)生隨機數(shù)的函數(shù) void bubbleSort(int *, int );//冒泡排序具體實現(xiàn)函數(shù) void swap(int *, int *);//兩個數(shù)字實現(xiàn)交換的函數(shù) void display(int *, int );//在屏幕輸出結果函數(shù) int main() { const int N = 10;//定義常數(shù) int arr[N];//定義數(shù)組 srandData(arr, N); bubbleSort(arr, N); display(arr, N); return 0; } void srandData(int *a, int n) { srand(time(NULL)); for(int i = 0; i < n; i++) { a[i] = rand() % 50;//取50以下的數(shù)字 cout << a[i] << " "; } cout << endl; } void swap(int *b, int *c) { int temp = *c; *c = *b; *b = temp; } void bubbleSort(int *a, int n) { for(int i = 0; i < n; i++) { for(int j = 0; j < n - i - 1; j++) { if(a[j] < a[j + 1]) { swap(&a[j], &a[j + 1]);//兩者交換 } } } } void display(int *d, int n) { for(int i = 0; i < n; i++) { cout << d[i] << " "; } cout << endl; }
以上就是c語言冒泡排序怎樣實現(xiàn)從大到小的詳細內(nèi)容,更多請關注億速云其它相關文章!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。