#include<iostream>
#include<stdlib.h> //Ubuntu中的亂數需具此HeadFile
#include<time.h>
#include<iomanip>
using namespace std;
#define size 10
#define start 0
void Swap(int &a,int &b)
{
int buf;
buf = a;
a = b;
b = buf;
}
void BubbleSort(int array[])
{
for(int i = size-1;i>start;i--)
{
for(int j = start;j<i;j++)
{
if( array[j] > array[j+1] )
Swap(array[j],array[j+1]);
}
}
}
int main()
{
srand(time(0));
int *array = new int[size];
cout<<"Oringinal List: ";
for(int i=start;i<size;i++)
{
array[i] = i;
array[i] = rand()%20+1; //1~20
cout<<setiosflags(ios::right)<<setw(5)<<array[i];
}
cout<<endl<<endl;
BubbleSort(array);
cout<<"After List: ";
for(int j=start;j<size;j++)
{
cout<<setiosflags(ios::right)<<setw(5)<<array[j];
}
cout<<endl<<endl;
return 0;
}
執行結果: