C++总结笔记(六)排序算法之冒泡排序

冒泡排序

  1. 对于需要排序的序列垂直排列,从无序区底部向上扫描,若重者在上,轻者在下,则交换位置;如此反复,直到所有重者在下,轻者在上为止;
  2. 冒泡算法的最好时间复杂度:已经排好序的序列,比较次数为n-1次,移动次数为0,所以时间复杂度为O(n);
  3. 冒泡算法的最差时间复杂度:如果是倒序的序列,移动次数n(n+1)/2次,时间复杂o(n2);
  4. 冒泡排序平均时间复杂度为:o(n2);
  5. 冒泡排序时就地排序,稳定性好;

#include<iostream>
using namespace std;

void BubbleSort(int * pData,int count)
{
 int tem;
 int exchange = 0;

 for(int i=0; i<count; i++)
 {
  for(int j=count-1; j>i; j--)
  {
   if(pData[j] < pData[j-1])
   {
    exchange++;
    tem = pData[j-1];
    pData[j-1] = pData[j];
    pData[j] = tem;
   }
  }
 }
 cout<<"交换了:"<<exchange<<"次!"<<endl;
}

int main()
{
 int array[] = {7,6,5,4,3,2,1};
 int count = sizeof(array)/sizeof(int);

 BubbleSort(array,count);

 for(int a=0; a<7; a++)
 {
  cout<<array[a]<<endl;
 }
}

原文地址:https://www.cnblogs.com/huochangjun/p/3099597.html