排序——冒泡排序

#include <iostream>
using namespace std;

void BubbleSort(int k[] , int n)//传入数组和数组的长度
{
    int i , j ,temp , count1=0,count2=0,flag=1;
    
    for( i=0; i < n-1 && flag ;i++ )
    {
        for( j=n-1; j > i; j-- )
        {
            count1++;
            flag=0;
            if( k[j-1] > k[j] )
            {
                count2++;
                temp = k[j-1];
                k[j-1] = k[j];
                k[j] = temp;
                flag=1;
                
            }
        }
    }
    
    cout << "比较次数:"  << count1 << " 移动次数:"  <<  count2 << endl;
} 

int main()
{
    int i ,a[10] = {5,2,6,0,3,9,1,7,4,8};
    
    BubbleSort(a,10);
    
    for( i=0; i < 10 ;i++ )
    {
        cout << a[i];
    }
    
    cout << endl;
    
    return 0;
}
原文地址:https://www.cnblogs.com/xieyupeng/p/6979297.html