计数与负整数排序

时间:2017-05-18 13:57:53

标签: algorithm sorting

我理解正整数的计数排序算法,但我如何修改它以处理负整数?

1 个答案:

答案 0 :(得分:-1)

我在这里编写了一些东西,它可以称为计数排序,我在这里使用哈希映射。

所以对于这个例子,我假设我的数组就像

int a[] = {-3,-1,2,4,-2,-2,5,6};

现在这是我算法的流程: -

1. Declare a map - map<int, int> m; // it keeps the count of each array element.
2. Iterate through your array and keep making a count increment.
3. With this for loop keep track of minimum and maximum element present in the array.
4. Now start another loop from minimum number to maximum number and based on the count for that element, print it out.

以下是它的工作代码: -

#include <bits/stdc++.h>

using namespace std;

int main()
{
   int a[] = {-3,-1,2,4,-2,-2,5,6};
   map<int, int> m;
   int len = sizeof(a)/sizeof(*a);
   int min_num = INT_MAX;
   int max_num = INT_MIN;
   for(int i=0; i<len; i++)
   {
      min_num = min(min_num, a[i]);
      max_num = max(max_num, a[i]);
      m[a[i]]++;
   }
   for(int i=min_num; i<=max_num; i++)
   {
      int count = m[i];
      if(count>0) 
      {
         for(int j=0; j<count; j++)
         {  
            cout<<i<<" ";
         }   
      }
   }
   cout<<endl;
   return 0;
}

希望这有帮助!

相关问题