zoukankan      html  css  js  c++  java
  • 计数排序

    数组A[N]

    算法思想:

    1.找出序列中最大的数Max,则序列的范围为0-k;

    2.计算每个数出现的次数,用临时数组temp[Max+5]保存(遍历数组,temp[a[i]]++),注:要确保temp的长度>A的长度

    3.计算<=i的元素的个数,0-Max都计算一遍

    4.根据上一步可以确定<=a[i]的个数,从而将a[i]放在最终位置上

     1 void CountSort(int a[], int n,int result[])
     2 {
     3     int max=a[0];
     4     for (int i = 1; i < n; i++)   //找到最大值,确定数组中值的范围
     5     if (a[i]>max)
     6         max = a[i];
     7     int *temp = new int[max+1];
     8     for (int i = 0; i < max + 1;i++) 
     9         temp[i] = 0;
    10     for (int j = 0; j < n; j++)   //此时temp[i]中存储的是元素i出现的次数
    11         temp[a[j]]++;
    12     for (int k = 1; k <= max; k++)
    13         temp[k] += temp[k - 1];  //此时temp[i]中存储的是小于等于i的元素个数
    14     for (int m = n-1; m >= 0; m--)   //从后向前遍历,因为数组a中可能存在相同的元素
    15     {
    16         result[temp[a[m]]-1] = a[m];     //<=m的元素有temp[a[m]]个,所以a[m]放在第temp[a[m]]位置上
    17         temp[a[m]]--;          //剩下的数中,<=a[m]的元素个数减一
    18     }
    19     delete []temp;
    20 }

    时间复杂度:O(n+max)

    空间复杂度:O(n+max)

  • 相关阅读:
    cf B. Vasily the Bear and Fly
    hdu 3339 In Action
    hdu 六度分离
    cf A. Vasily the Bear and Triangle
    cf C. Secrets
    2.19学习笔记|2.20学习笔记
    VAE代码学习
    2.9日学习记录
    deconvolution反卷积(待学习)
    gamma分布学习
  • 原文地址:https://www.cnblogs.com/mrlsx/p/5846987.html
Copyright © 2011-2022 走看看