1 Star 0 Fork 5

卢国祥/C Data Structure

forked from Shapper/C Data Structure 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
radix_sort.h 1.54 KB
一键复制 编辑 原始数据 按行查看 历史
Shapper 提交于 2年前 . add radix sort
//
// Radix Sort
// Created by Win10 on 2023/4/8.
//
#ifndef C_DATA_STRUCTURE_RADIX_SORT_H
#define C_DATA_STRUCTURE_RADIX_SORT_H
#include <algorithm>
template<typename T>
// A utility function to get maximum value in arr[]
T getMax(T a[], int len)
{
T mx = a[0];
for (int i = 1; i < len; i++)
if (a[i] > mx)
mx = a[i];
return mx;
}
template<typename T>
// A function to do counting sort of arr[] according to
// the digit represented by exp.
void countSort(T a[], int len, int exp)
{
T output[len]; // output array
int i, count[10] = { 0 };
// Store count of occurrences in count[]
for (i = 0; i < len; i++)
count[(a[i] / exp) % 10]++;
// Change count[i] so that count[i] now contains actual
// position of this digit in output[]
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
// Build the output array
for (i = len - 1; i >= 0; i--) {
output[count[(a[i] / exp) % 10] - 1] = a[i];
count[(a[i] / exp) % 10]--;
}
// Copy the output array to arr[], so that arr[] now
// contains sorted numbers according to current digit
for (i = 0; i < len; i++)
a[i] = output[i];
}
template<typename T>
//LSD(Least Significant Digit first)
void radix_sort(T a[], int len) {
// Find the maximum number to know number of digits
int m = getMax(a, len);
// Do counting sort for every digit. Note that instead
// of passing digit number, exp is passed. exp is 10^i
// where i is current digit number
for (int exp = 1; m / exp > 0; exp *= 10)
countSort(a, len, exp);
}
#endif //C_DATA_STRUCTURE_RADIX_SORT_H
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C/C++
1
https://gitee.com/noob-coder/c-data-structure.git
git@gitee.com:noob-coder/c-data-structure.git
noob-coder
c-data-structure
C Data Structure
master

搜索帮助