冒泡排序
冒泡法排序就是将需要排序内容从第一个元素开始,与相邻元素比较大小,将较大的/较小的放到后边,第一次遍历最后一个元素是最大/最小。
依次类推,第二次将倒数第二大/第二小元素放到倒数第二的位置。直到全部元素按照顺序排列。
比如5个元素:
第一次遍历 需要比较4次(相邻元素之间比较,最坏情况)
第二次遍历 比较3次
...
第四次遍历 比较1次
所以算法复杂度是n*(n-1)/2
#include<iostream>
using namespace std;
void display(int array[], int n)
{
for(int count=0;count<n;count++) //print all items of array
{
cout<<array[count]<<'\t';
}
cout<<endl;
}
int bubble_sort(int array[], int n)
{
int temp=0,count=0 ; //set an temporary variable
cout<<"debug information:"<<endl;
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(array[j]>array[j+1])
{
temp=array[j+1];
array[j+1]=array[j];
array[j]=temp;
count++;
}
display(array,n );
}
}
cout<<count<<endl;
return 0;
}
int main()
{
int array[5]={35,14,3,02,-1};
int num_array=sizeof(array)/sizeof(int); //获取数组长度
cout<<"before sort the array is :"<<endl;
display(array,num_array);
bubble_sort(array,num_array);
cout<<"after sort the array is :"<<endl;
display(array,num_array);
system("pause");
return 0;
}