常用排序-冒泡法排序

冒泡排序

冒泡法排序就是将需要排序内容从第一个元素开始,与相邻元素比较大小,将较大的/较小的放到后边,第一次遍历最后一个元素是最大/最小。

依次类推,第二次将倒数第二大/第二小元素放到倒数第二的位置。直到全部元素按照顺序排列。

比如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;
    } 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值