排序算法

2021-01-30  本文已影响0人  __method__

C++ 冒泡排序

#include <iostream>
using namespace std;
#define N 6
void bubble_sort(int a[], int n)
{
    int i, j, t;

    for(i=0; i<n-1; i++)
        for(j=0; j<n-1-i; j++)
            if(a[j]>a[j+1])
            {   t=a[j];  a[j]=a[j+1];  a[j+1]=t;}
}
int main()
{
//    int a[N];
//
//    cout<<"请输入"<<N<<"个数:"<<endl;
//    for(i=0; i<N; i++)
//        cin>>a[i];
    int a[N] = {8, 4, 9, 6, 5, 2};
    bubble_sort(a, N);
    cout<<"排好序的数为:"<<endl;
    for(int i=0; i<N; i++) cout<<a[i]<<'\t';
    cout<<endl;
}

选择排序

#include <iostream>
using namespace std;
#define N 6
void select_sort(int a[], int n)
{
    int i,j,p,t;

    for(i=0; i<n-1; i++)
    {
        p=i;
        for(j=i+1; j<n; j++)
            if(a[j]<a[p]) p=j;   //记下每一趟最小元素的下标
        if(p!=i)            // A行:请读者思考为什么需要此判断
        {   t=a[p]; a[p]=a[i]; a[i]=t;      }
    }
}
int main()
{
//    int a[N], i;
//
//    cout<<"请输入"<<N<<"个数:"<<endl;
//    for(i=0; i<N; i++)
//        cin>>a[i];
    int a[N] = {8, 4, 9, 6, 5, 2};
    select_sort(a, N);
    cout<<"排好序的数为:"<<endl;
    for(int i=0; i<N; i++)
        cout<<a[i]<<'\t';
    cout<<endl;
}

变种

#include <iostream>
using namespace std;
#define N 6
void select_sort(int a[], int n)    //选择法排序的变种
{
    int i , j, t;

    for(i=0; i<n-1; i++)            //按升序排序
        for(j=i; j<n; j++)
            if(a[i]>a[j])
            {   t=a[i];  a[i]=a[j];  a[j]=t;  }
}
int main()
{
//    int a[N], i;
//
//    cout<<"请输入"<<N<<"个数:"<<endl;
//    for(i=0; i<N; i++)
//        cin>>a[i];
    int a[N] = {8, 4, 9, 6, 5, 2};
    select_sort(a, N);
    cout<<"排好序的数为:"<<endl;
    for(int i=0; i<N; i++)
        cout<<a[i]<<'\t';
    cout<<endl;
}

插入排序

#include <iostream>
using namespace std;
#define N 6

void ba_ins_sort(int a[], int n) //直接插入排序之后插算法
{
    int i, j, p;
    for(i=1; i<n; i++)
    {
        p=a[i];
        for(j=i-1; j>=0&&p<a[j]; j--)  //将比p大的元素依次右移一个位置
            a[j+1]=a[j];
        a[j+1]=p;
    }
}
int main()
{
//    int a[N], i;
//
//    cout<<"请输入"<<N<<"个数:"<<endl;
//    for(i=0; i<N; i++)
//        cin>>a[i];
    int a[N] = {8, 4, 9, 6, 5, 2};
    ba_ins_sort(a, N);
    cout<<"排好序的数为:"<<endl;
    for(int i=0; i<N; i++)
        cout<<a[i]<<'\t';
    cout<<endl;
}
上一篇 下一篇

猜你喜欢

热点阅读