基本思想:

在要排序的一组数中,对当前还未排好序的范围内的全部数,自上而下对相邻的两个数依次进行比较和调整,让较大的数往下沉,较小的往上冒。即:每当两相邻的数比较后发现它们的排序与排序要求相反时,就将它们互换。

算法实现:(HDU 1040 亲测 AC)

#include<iostream>
using namespace std;
const int N =1005;
void BubbleSort(int a[],int );
void print(int a[],int num);
void swap(int &a,int &b);

int main()
{
    int s[N];
    int T;
    cin>>T;
    while(T--)
    {
        int n;
        cin>>n;
        for(int j=0;j<n;j++)
           cin>>s[j];
        BubbleSort(s,n);
        print(s,n);       
        cout<<endl;        
    }
    return 0;
}
void BubbleSort(int a[],int num)//冒泡排序算法 
{
    for(int i=0;i<num-1;i++)
    {
        for(int j=0;j<num-i-1;j++)
        {
            if(a[j]>a[j+1])
            {
                swap(a[j],a[j+1]);
            }
        }
    }
}
void swap(int &a,int& b)//交换元素 
{
    int temp;
    temp=a;
    a=b;
    b=temp;
}
void print(int a[],int n)//输出数组元素 
{
    cout<<a[0];
    for(int k=1;k<n;k++)
    {
        cout<<" "<<a[k];
    }
}
View Code

相关文章:

  • 2022-12-23
  • 2021-10-07
  • 2021-06-06
  • 2022-03-10
  • 2021-10-07
  • 2021-06-22
猜你喜欢
  • 2021-08-27
  • 2021-06-04
  • 2021-12-26
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案