Implementation and testing of radix sorting

Source: Internet
Author: User

The Cardinal sort process does not need to compare keywords, but instead uses the "assign" and "collect" procedures to achieve sorting. Their time complexity can reach the linear Order: O (n), is a stable sort

The implementation of the cardinality sort (in the form of an array, also through a linked list)

#pragma once    //radix sort

#include <iostream>
using namespace std;


#include <stdio.h>
#include <stdlib.h>

int get_max (int arr[], int n)
{
    int i;
    int max = 0;
    for (i = 0; i < n; i++)
        if (Arr[i] > Max)
            max = arr[i];
    return max;
}

void Count_sort (int arr[], int n, int exp)
{

    int i, count[10] = {0};
    int output[10];

    for (i = 0; i < n; i++)
        count[(Arr[i]/exp)% 10]++;

    for (i = 1; i < i++)
        Count[i] + = count[i-1];

    for (i = n-1; I >= 0; i--)
    {
        output[count[(Arr[i]/exp)%]-1] = arr[i];
        count[(Arr[i]/exp)% 10]--;
    }

    for (i = 0; i < n; i++)
        arr[i] = Output[i];
}

void Radix_sort (int arr[], int n)
{
    int exp;
    int m = Get_max (arr, n);
    for (exp = 1; m/exp > 0; exp *=)
        count_sort (arr, n, exp);
}

Test file for cardinality sorting

void Main ()//Cardinal sort, implemented in array way {int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};

    int n = sizeof (arr)/sizeof (arr[0]);
    Radix_sort (arr, n);
    for (int i = 0; i < n; i++) {cout<<arr[i]<< "";
} cout<<endl; }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.