冒泡排序

#include <iostream>

using namespace std;

int a[1000];

int main()
{
    cin >> n;
    for(int i = 0;i < n; i ++)
        cin >> a[i];
    for (int i = 0; i < n; i ++)
        for (int j = 0; j < n - i; j ++)
            if (a[i] > a[j])
                swap(a[i], a[j]);
}

插入排序

插入排序就像摸牌一样,将数列从第二个数开始逐个插入应该存在的位置,时间复杂度与冒泡排序相当。

//升序 
void isort(int a[],int n){
    for (int i = 1;i < n;i++){
        int t = a[i];
        int j = i - 1;
        while (t < a[j] && j >= 0){
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = t;
    }
    for (int i=0;i<n;i++)
            printf("%d ",a[i]);
}
//降序 
void isort(int a[],int n){
    for (int i = 1;i < n;i++){
        int t = a[i];
        int j = i - 1;
        while (t > a[j] && j >= 0){
            a[j+1] = a[j];
            j--;
        }
        a[j+1] = t;
    }
    for (int i=0;i<n;i++)
            printf("%d ",a[i]);
}

堆排序

有手就行

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 1e6 + 10;

int n, m;
int siz;

int a[N];

void down(int i)
{
    int t = i;
    if (i * 2 <= siz && a[t] > a[i * 2])
    {
        t = i * 2;
    }
    if (i * 2 + 1 <= siz && a[t] > a[i * 2 + 1])
    {
        t = i * 2 + 1;
    }
    if (i != t)
    {
        swap(a[i], a[t]);
        down(t);
    }
}

int main()
{
    cin >> n >> m;
    for (int i = 1; i <= n; i ++)
    {
        scanf("%d", &a[i]);
    }

    siz = n;

    for (int i = n / 2; i; i --)
    {
        down(i);
    }

    while (m --)
    {
        printf("%d ", a[1]);
        a[1] = a[siz --];
        down(1);
    }
}
最后修改:2022 年 03 月 30 日
如果觉得我的文章对你有用,请随意赞赏