巧用数组下标

巧用数组下标

  • 数组的下标是一个隐含的很有用的数组,特别是在统计一些数字,或者判断一些整数型数是否出现过的时候。
  • 问题:给100个无序的 int 类型数组 A,并且这些整数的取值范围在 0-20 之间,要求在O(n)的时间复杂度中把这100个数按照从大到小的顺序打印出来。
//@author PzLu
//2019.05.14
//This is an O(n) sorted algorithm.

#include
using namespace std;
int main(){
     
    //tagged time
     clock_t start_time = clock();
    srand(unsigned(time(NULL)));
    const int min = 0;
    const int max = 20;
    //random numbers, Generate 100 random figures
    int A[200];
    for(int i = 0;i < 100; i++){
     
        A[i] = rand() % (max - min + 1) + min;
    }
    //Output the disordered numbers
    cout << "The random numbers are:" << endl;
    for(int i = 0;i < 100; i++){
     
        cout << A[i] << "\t";
    }
    cout << endl;
    //process the numbers
    cout << "The ordered numbers are:" << endl;
    int num[21] = {
     0};
    for(int index = 0; index < 100; index++){
     
        num[A[index]]++;
    }
    for(int i = 0; i < 21; i ++){
     
        for(int j = 0; j < num[i]; j++){
     
            cout << i << " ";
        }
    }
    cout << endl;
    //time display
    cout << "The elapsed time is: " << double(clock()-start_time) << "s" << endl;
    cout << endl;
    return 0;
}

你可能感兴趣的:(小算法)