冒泡排序算法示例ios
算法原理算法
冒泡排序算法的運做以下:(從後往前)數組
動畫演示:動畫
下面是算法程序示例:spa
//POWERED BY DRAGONIR #include<iostream> #include<cstdlib> #include<cstdio> #include<ctime> #define SIZE 10 using namespace std; void bubbleSort(int * a, int len){ int temp; for(int i=0; i<len ; i++ ){ for(int j=len-1; j>i; j--){ if(a[j-1]>a[j]){ temp=a[j-1]; a[j-1]=a[j]; a[j]=temp; } } cout<<"第"<<i<<"部排序結果爲:"; for(int k=0; k<len; k++){ cout<<a[k]<<" "; } cout<<endl; } } int main(){ int array[SIZE]; srand(time(NULL)); for(int i=0 ; i<SIZE; i++){ array[i]=rand()/1000+100; } cout<<"排序前的數組爲:\n"; for(int i=0; i<SIZE; i++){ cout<<array[i]<<" "; } cout<<endl; bubbleSort(array, SIZE); cout<<"排序後的數組爲:\n"; for(int i=0 ; i<SIZE; i++){ cout<<array[i]<<" "; } cout<<endl; return 0; }
執行結果:blog