BubbleSort
生活随笔
收集整理的這篇文章主要介紹了
BubbleSort
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++ 冒泡排序 以及優化
原理:
代碼實現:
#include <iostream>using namespace std;void swap( int& a,int& b ) {int temp=a;a=b;b=temp;} //最基本的冒泡排序 void BubbleSort_01(int array[],int length) {for(int i=0;i<length;i++){for(int j=0;j<length-i-1;j++){if(array[j]>array[j+1]){swap(array[j],array[j+1]);}}} }void BubbleSort_02(int array[],int length) {bool is_sorted=true;//記錄數組是否已經有序,減少比較輪次for(int i=0;i<length;i++){for(int j=0;j<length-i-1;j++){if(array[j]>array[j+1]){swap(array[j],array[j+1]);is_sorted=false;}}if(is_sorted)break;} } //基于半有序數組的優化 eg: p[]={5 4 3 2 6 7 8 9} void BubbleSort_03(int array[],int length) {bool is_sorted=true;int unsorted_border=length-1;int last_index=0;//記錄無序數組的最右下標for(int i=0;i<length;i++){for(int j=0;j<unsorted_border;j++){if(array[j]>array[j+1]){swap(array[j],array[j+1]);is_sorted=false;last_index=j;}}unsorted_border=last_index;//更新無序數組邊界,下一輪只比較到該下標位置if(is_sorted)break;} } int main() {cout << "please input the length of array:" << endl;int n;cin>>n;int *p=new int[n];cout << "please input the data of array:" << endl;for(int i=0;i<n;i++)cin>>p[i];cout << "執行BubbleSort:" << endl;BubbleSort_01(p,n);for(int i=0;i<n;i++)cout<<p[i]<<" ";return 0; }總結
以上是生活随笔為你收集整理的BubbleSort的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [html] H5的video可以播放
- 下一篇: eclipse及tomcat设置编码