冒泡法排序C++实现

来源:互联网 发布:clock 算法 编辑:程序博客网 时间:2024/06/11 03:12

看一下代码:

#include <iostream>using namespace std;//function count the number of count variablevoid printf(int* a, int count){    for (int i = 0; i< count; i++)    {        cout << a[i] <<" ";    }    cout << endl;}void BubbleSort(int *a, int count){    int i,j,k,temp;    for(i=0;i<count-1;i++)    {        k=i;        for(j=i+1; j<count; j++)        {        if(*(a+j) < *(a+k))k=j;        temp=*(a+k);        *(a+k)=*(a+i);        *(a+i)=temp;        }        cout<<"The"<<i<<"round:"<<endl;        printf(a,count);    }}int main(){    int data[]={6, 5, 4, 3, 2, 1};//initialize data[]    BubbleSort(data, 6);    cout<<"The sort result:"<<endl;    printf(data, 6);    return 0;}

最后运行结果:


网上找到网友的另外一种冒泡法排序,代码如下:

void BubbleSort(int* pData, int count){    int temp;    for (int i = 1; i < count; i++)    {        for (int j = count - 1; j >= i; j--)        {            if (pData[j] < pData[j - 1])            {            temp = pData[j - 1];                pData[j - 1] = pData[j];                pData[j] = temp;            }        }        cout << "The "<< i <<" round:" << endl;        print(pData, count);        cout << "----------------------------" << endl;    }}
其采用倒序查询的方式排序,最后结果相同相同。


冒泡法冒泡排序

优点:比较简单,空间复杂度较低,是稳定的;

缺点:时间复杂度太高,效率不好。

0 0