C++ 冒泡、插入和选择排序

来源:互联网 发布:java 密码加密解密 编辑:程序博客网 时间:2024/06/05 06:08
#include<iostream>
using namespace std;
void maopao(int a[], const int n)//冒泡排序
{
    for(int i = 0; i < n;i++)
    for (int j = 0; j < n - i-1; j++)
    {
        if (a[j]>a[j + 1])
        {
            int temp = a[j];
            a[j] = a[j + 1];
            a[j + 1] = temp;
        }
    }
}
void ins(int a[], const int n)//插入排序
{
    for (int i = 0; i < n-1; i++)
    {
       if (a[i+1]<a[i])
        {
            int temp = a[i+1];
            int j =0;
            while (temp >= a[j])
            {
                j++;
            }
            int k = i+1;
            while (k>=j)
            {
                a[k] = a[k-1];
                k--;
            }
            a[j] = temp;
        }
    }


}
int min_pos(int a[], int k, int n)//计算数组a[],从k-n之间最小数的位置,记为pos,为选择排序准备
{
    int pos = k-1;
    for (int i = k-1; i <n; i++)
    {
        if (a[pos]>a[i])
            pos = i;
    }
    return pos;
}
void choose(int a[], const int n)//选择排序
{
    for (int i = 1; i <=n; i++)
       for (int t = i; t<= n; t++)
    {
        int p = min_pos(a, t, n);
        if (p != t-1)
        {
            int tem = a[p];
            a[p] = a[t-1];
            a[t - 1] = tem;
        }
    }

    
}

void show(const int a[],const int n)
{
    for (int i = 0; i < n; i++)
    {
        cout << a[i] << '\t';
    }

}
int main()
{
    int a[10]{4, 5, 6, 9, 8, 7, 1, 2, 3, 0};
    maopao(a, 10);//冒泡
    show(a, 10);
    ins(a, 10);//插入
    show(a, 10);
    choose(a, 10);//选择
    show(a, 10);
    return 0;

}
0 0