基数排序

首先定义下基数排序的规则。即根据个位上的数排序------>根据十位上的数排序------>根据百分位上的数排序------>根据千分位上的数排序------>依此类推......这样的话,我们首先分析一次排序的过程,之后的多次排序原理都是一样的。

依据个位上的数字排序:

这个第一步肯定是要先获取个位上的数字,获取个位数字的方法,即对10求余即可。(获取十位数字对100求余得到如12,再除以10即可得到十位上的数字)。

第二步:将个位数字进行比较,存入新的数组中

第三步:根据个位数字排序比较的结果数组,将原数组元素的个位数等于第二步得到的个位数排序数组,进行遍历比较,即可得到原数组按个位数进行排序的结果。

至此,按照个位排序的过程结束。

那么基数排序的整体过程为:循环体

{

获取某一位上的数;

将这一位上的数进行排序;

将数组中这一位上的数与第二步排序结果进行比对,进行排序

}

代码实现如下:(代码实现参考网上大神的方法)

#include"string.h"
#include<stdlib.h>
#include<assert.h>
#include<iostream>
using namespace std;
int pre_process_data(int array[], int length, int weight)  
{  
    int index ;  
    int value = 1;  
  
    for(index = 0; index < weight; index++)  
        value *= 10;  
  
    for(index = 0; index < length; index ++)  
        array[index] = array[index] % value /(value /10);  
  
    for(index = 0; index < length; index ++)  
        if(0 != array[index])  
            return 1;  
  
    return 0;  
}  

void sort_for_basic_number(int array[], int length, int swap[])  
{  
    int index;  
    int basic;  
    int total = 0;  
  
    for(basic = -9; basic < 10; basic++){  
        for(index = 0; index < length; index++){  
            if(-10 != array[index] && basic == array[index] ){  
                swap[total ++] = array[index];  
                array[index] = -10;  
            }  
        }  
    }  
  
    memmove(array, swap, sizeof(int) * length);  
}  

void sort_data_by_basic_number(int array[], int data[], int swap[], int length, int weight)  
{  
    int index ;  
    int outer;  
    int inner;  
    int value = 1;  
  
    for(index = 0; index < weight; index++)  
        value *= 10;  
  
    for(outer = 0; outer < length; outer++){  
        for(inner = 0; inner < length; inner++){  
            if(-10 != array[inner] && data[outer]==(array[inner] % value /(value/10))){  
                swap[outer] = array[inner];  
                array[inner] = -10;  
                break;  
            }  
        }  
    }  
  
    memmove(array, swap, sizeof(int) * length);  
    return;  
}  

void radix_sort(int array[], int length)  
{  
    int* pData;  
    int weight = 1;  
    int count;  
    int* swap;  
    if(NULL == array || 0 == length)  
        return;  
  
    pData = (int*)malloc(sizeof(int) * length);  
    assert(NULL != pData);  
    memmove(pData, array, length * sizeof(int));  
  
    swap = (int*)malloc(sizeof(int) * length);  
    assert(NULL != swap);  
  
    while(1){  
        count = pre_process_data(pData, length, weight);  
        if(!count)  
            break;  
  
        sort_for_basic_number(pData, length, swap);  
        sort_data_by_basic_number(array, pData, swap, length, weight);  
        memmove(pData, array, length * sizeof(int));  
        weight ++;  
    }  
  
    free(pData);  
    free(swap);  
    return;  
}  

int main()
{
	int a[6]={1,2,3,5,2,3};
	radix_sort(a,6);
	for(int i=0;i<6;i++)
	{
		cout<<a[i]<<endl;
	}
	system("pause");
}


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