国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學(xué)院 > 開發(fā)設(shè)計 > 正文

冒泡排序算法以及改進(jìn)

2019-11-08 02:19:42
字體:
供稿:網(wǎng)友

為了能給老是忘記的自己做個筆記。

冒泡排序(升序)的思想就是將最大的數(shù)逐步后移,例如:arr[n] ={5, 9, 8, 6, 7},i從數(shù)組下標(biāo)0開始,j從數(shù)組下標(biāo)n-1開始,依次將arr[j]與arr[j-1]比較,如果arr[j] < arr[j-1]就將arr[j]與arr[j-1]交換,直到j(luò) = i;

C++代碼:

#include <iostream>using namespace std;void swap(int *a, int *b){ int t; t = *a; *a = *b; *b = t;}void sort(int p[], int n){ for(int i = 0; i < n; i++){ for(int j = n-1; j > i; j--){ if(p[j] < p[j-1]){ swap(&p[j], &p[j-1]); } } } for(int i = 0; i < n; i++){ cout << p[i] <<" "; }}int main(){ int n, *p; cin >> n; p = new int[n]; for(int i = 0; i < n; i++){ cin >> p[i]; } sort(p, n); return 0;}

改進(jìn):設(shè)置bool型變量temp,當(dāng)上一次循環(huán)沒有交換元素則證明排序已經(jīng)完成,無需進(jìn)行下一次排序,直接跳出循環(huán)。

C++代碼:

#include<iostream>using namespace std;void swap(int *a, int *b){ int t; t = *a; *a = *b; *b = t;}void sort(int p[], int n){ bool temp; //設(shè)置變量,如果上次循環(huán)沒有交換則停止排序 for(int i = 0; i < n; i++){ temp = 0; for(int j = n-1; j > i; j--){ if(p[j] < p[j-1]){ temp = 1; swap(&p[j], &p[j-1]); } } if(temp == 1) break; } for(int i = 0; i < n; i++){ cout << p[i] <<" "; }}int main(){ int n, *p; cin >> n; p = new int[n]; for(int i = 0; i < n; i++){ cin >> p[i]; } sort(p, n); return 0;}
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 安西县| 甘孜县| 武定县| 西林县| 文安县| 高邮市| 延川县| 阳春市| 商洛市| 浦东新区| 华坪县| 阿克| 祁连县| 农安县| 志丹县| 永顺县| 南丰县| 乐清市| 岳阳市| 新郑市| 城市| 昌乐县| 朝阳市| 田东县| 宾川县| 定兴县| 望江县| 湄潭县| 陵水| 长治市| 莆田市| 兴国县| 桑植县| 太原市| 五指山市| 扶沟县| 正定县| 湖口县| 绥江县| 靖西县| 宣威市|