经典算法之冒泡指针

来源:互联网 发布:淘宝买iphone7靠谱商家 编辑:程序博客网 时间:2024/05/21 20:10

//冒泡指针即,分别用两个指针指向数组中的两个数,如果第一个大于第二个,则交换。反之则不变,这样,第一遍后 最后一个值肯定为最大的,这样进行多次循环比较后 即满足从小到大的排列;若从大到小 则只要将条件改为第一个小于第二个人即可;

#include <iostream>  

using namespace std;  
  
void print(int* pData, int count)
{
    for (int i = 0; i< count; i++)
{  
   cout << pData[i] <<"  ";
    }  
    cout << endl;  
}  
  
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;  
    }  
}  
  
int main()  
{  
int data[] = {10, 8, 9, 7, 4,1,6}; 
    BubbleSort(data, 7);  
    cout << "The sort result:" << endl;  
    print(data, 7);  
    return 0;  
}  
原创粉丝点击