计数排序

#include <iostream>
#include <string.h>
#include <stdlib.h>

using namespace std;

void CountSort(int arr[],int n)
{
    if(arr == NULL || n <= 0)
    {
        return ;
    }
    int MIN = arr[0];
    int MAX = arr[0];
    for(int i=1;i<n;i++)
    {
        if(arr[i] > MAX)
        {
            MAX = arr[i];
        }
        if(arr[i] < MIN)
        {
            MIN = arr[i];
        }
    }
    int *temp = new int[MAX-MIN+1];
    memset(temp,0,sizeof(temp));
    for(int i=0;i<n;i++)
    {
        temp[arr[i]-MIN]++;
    }
    for(int i=1;i< (MAX-MIN+1);i++)
    {
        temp[i] += temp[i-1];
    }
    int *temp_arr = new int[n];
    for(int i=0;i<n;i++)
    {
        temp_arr[--temp[arr[i]-MIN]] = arr[i];
    }
    for(int i=0;i<n;i++)
    {
        arr[i] = temp_arr[i];
    }
    delete []temp_arr;
    temp_arr = NULL;
    delete []temp;
    temp = NULL;
}


int main()
{
    int arr[20] = {3,6,5,3,6,3,6,9,4,5,4,3,6,4,5,5,5,4,5,4};
    CountSort(arr,20);
    for (int i=0;i<20;i++)
    {
        cout<<arr[i]<<" ";
    }
    return 0;
}

你可能感兴趣的:(计数排序)