Counting Sort achieve Detailed

What counts is the sort

A sorting algorithm to sort the count is not based on the comparison. Its advantage is that when the sorting integers within a certain range, its complexity is Ο (n + k) (where k is an integer in the range), faster than any sorting algorithm comparison. Of course, this is a sacrifice space for time approach.

Moving map presentation

* FIG movable from novice tutorial

Method to realize

For example, it is known to be sorted array of ranges of numbers, use the fastest speed to sort.
If the range of 1-9, as shown in FIG moving above
a, find the maximum and minimum array
two, to establish a max-min+1array of space, each element of the initial value 0
Third, to traverse the sorted random array
example, the first number is 2, then the element array subscript 2 plus 1
second number is 3, the subscript of the array element 3 plus 1
so
four, in the end, we get an array, the array each value represents the number of index values appear in the sorted array.
Fifth, we get directly through the array, the output index value, the value of the number of elements, it is output several times.

Sort completion

In the case where the range is not large, sort performance count even faster than O ( n   l O g n ) O(n\ log n) ordering

Performance parameters concerning the ranking count

1, time complexity

O ( n ) O (n)

2, space complexity

O ( n ) O (n)

3, is stable

stable

Code

/*
 * @Descripttion: 
 * @version: 
 * @Author: edisonhuang
 * @Date: 2020-03-12 16:17:54
 * @LastEditors: edisonhuang
 * @LastEditTime: 2020-03-12 16:32:34
 */
#include <iostream>
void Print(int arr[], int length);
void CountSort(int arr[],int length);
using namespace std;

int main()
{   
    int arr[] = {13, 14, 8, 100, 25, 75, 9, 64, 12};
    int len = (int) sizeof(arr) / sizeof(*arr);
    Print(arr, len);
    CountSort(arr, len);
    Print(arr, len);
    
    return 0;
}

void CountSort(int arr[],int length){
    // 找最大值和最小值
    int max,min;
    max = arr[0];
    min = arr[0];
    for (int i = 0; i < length; i++)
    {
        if(arr[i] > max)
        {
            max = arr[i];
        }
        if(arr[i] < min)
        {
            min = arr[i];
        }
        
    }
    //根据最大最小值开辟数组
    int *count;
    count = (int *)malloc(sizeof(int ) * (max-min+1));
    memset(count,0,sizeof(int ) * (max-min+1));

    // 统计原数组各值个数
    for (int i = 0; i < length; i++)
    {
        count[arr[i]-min]++;
    }
    // 放回原数组
    int j = 0;
    for (int  i = 0; i < max-min+1; i++)
    {
        while (count[i] !=0 )
        {
            arr[j] = i+min;
            j++;
            count[i]--;
        }
        
    }
    
    
}

void Print(int arr[], int length)
{
    for (int i = 0; i < length; i++)
    {
        cout << arr[i] << " ";
    }
    cout << endl;
}
Published 35 original articles · won praise 1 · views 1841

Guess you like

Origin blog.csdn.net/qq_40672635/article/details/104822023