sort

本文介绍了几种常见的排序算法,包括插入排序、归并排序、快速排序、堆排序和计数排序,并提供了详细的C++代码实现。每种算法都有其特点和适用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstring>
#include <cstdio>
#include <cmath>
#include <iostream>
#include <algorithm>
using namespace std;
const int INF = 1<<30;
const int MAXN = 100;
int A[MAXN], n;
int L[MAXN], R[MAXN]; // merge_sort
int heap_size;
#define left(i) (2*(i)+1)
#define right(i) 2*(i+1)

void insert_sort()
{
    for(int i=1; i<n; i++) {
        int key = A[i];
        int j = i-1;
        while(j>=0 && A[j]>key) {
            A[j+1] = A[j];
            j--;
        }
        A[j+1] = key;
    }
}

void combine(int x, int m, int y)
{
    memcpy(L, A+x, sizeof(A[0])*(m-x));
    memcpy(R, A+m, sizeof(A[0])*(y-m));
    L[m-x] = R[y-m] = INF;
    int l=0, r=0, k=x;
    while(k < y) {
        if(L[l] <= R[r]) {
            A[k++] = L[l++];
        } else {
            A[k++] = R[r++];
        }
    }
}

void merge_sort(int x, int y)
{
    if(y-x > 1) {
        int m = x + (y-x)/2;
        merge_sort(x, m);
        merge_sort(m, y);
        combine(x, m, y);
    }
}


int part(int x, int y)
{
    int key = A[y-1];
    int j=x-1;
    for(int i=x; i<y-1; i++) {
        if(A[i] < key) {
            swap(A[i], A[++j]);
        }
        i++;
    }
    swap(A[++j], A[y-1]);
    return j;
}

void quick_sort(int x, int y)
{
    if(y-x <= 1) return;
    int m = part(x, y);
    quick_sort(x, m);
    quick_sort(m+1, y);
}


void max_heapify(int i)
{
    int n = i;
    if(left(i)<heap_size && A[left(i)]>A[n]) {
        n = left(i);
    }
    if(right(i)<heap_size && A[right(i)]>A[n]) {
        n = right(i);
    }
    if(n != i) {
        swap(A[n], A[i]);
        max_heapify(n);
    }
}

void build_max_heap()
{
    heap_size = n;
    for(int i=(n-2)/2; i>=0; i--) {
        max_heapify(i);
    }
}

void heap_sort()
{
    build_max_heap();
    for(int i=n-1; i>0; i--) {
        swap(A[0], A[i]);
        --heap_size;
        max_heapify(0);
    }
}

void print()
{
    for(int i=0; i<n; i++) {
        printf("%d ", A[i]);
    }
    printf("\n");
}


int c[101];
void count_sort()
{
    memset(c, 0, sizeof(c));
    for(int i=0; i<n; i++) {
        ++c[A[i]];
    }
    int j=0;
    for(int i=0; i<101; i++) {
        while(c[i]) {
            A[j++] = i;
            c[i]--;
        }
    }
}


int main(){
    #ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
    #endif
    while(scanf("%d", &n) == 1) {
        for(int i=0; i<n; i++) {
            scanf("%d", &A[i]);
        }
        print();
        //insert_sort();
        //merge_sort(0, n);
        //quick_sort(0, n);
        //heap_sort();
        count_sort();
        print();
        printf("\n");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值