Learning algorithm starts from 0 - sorted (sort count 1.6)

Simple ranking method. Can then the O (n + k) time complexity sort the array, n is the length of the array, k is the maximum array number.

Original array:

2 1 7 3 5 8 2

 

 

Statistics array:

num [i] represents the number of digital i 0 1 2 1 0 1 0 1 1
Subscript 0 1 2 3 4 5 6 7 8

 

 

 

 

 

Sort array:

1 2 2 3 5 7 8

 

 

#include <algorithm>
#include <iostream>
#include <cstring>
#include <vector>
#include <cstdio>
#include <cmath>
#include <queue>

using namespace std;

const int maxn=1e5+1;
int n;
int A[maxn];
int T[maxn];//辅助数组。


int main(){
    scanf("%d",&n);
    int k=0;    //数组的最大数
    for(int i=0;i<n;i++){
        scanf("%d",&A[i]);
        T[A[i]]++;
        if(A[i]>k)k=A[i];
    }
    for(int i=0,j=0;i<=k;i++){
        while(T[i]>0){
            A[j++]=i;
            T[i]--;
        }
    }
    for(int i=0;i<n;i++){
        printf("%d ",A[i]);
    }
    printf("\n");
    return 0;
}

 

Guess you like

Origin www.cnblogs.com/wz-archer/p/11687200.html