【數據結構】冒泡排序算法示例

冒泡排序算法示例ios

算法原理算法

冒泡排序算法的運做以下:(從後往前)數組

  1. 比較相鄰的元素。若是第一個比第二個大,就交換他們兩個。
  2. 對每一對相鄰元素做一樣的工做,從開始第一對到結尾的最後一對。在這一點,最後的元素應該會是最大的數。
  3. 針對全部的元素重複以上的步驟,除了最後一個。
  4. 持續每次對愈來愈少的元素重複上面的步驟,直到沒有任何一對數字須要比較

動畫演示:動畫

下面是算法程序示例: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

相關文章
相關標籤/搜索