download: 聚焦市场开发热门技术 手把手带你开发商业级社交 App
实例
include<stdio.h>
define MAX 20
//#define SHOWPASS
define BASE 10
void print(int *a, int n) {
int i;
for (i = 0; i < n; i++) {
printf("%d\t", a[i]);
}
}
void radixsort(int *a, int n) {
int i, b[MAX], m = a[0], exp = 1;
for (i = 1; i < n; i++) {
if (a[i] > m) {m = a[i];
}
}
while (m / exp > 0) {
int bucket[BASE] = {0};
for (i = 0; i < n; i++) {bucket[(a[i] / exp) % BASE]++;
}
for (i = 1; i < BASE; i++) {bucket[i] += bucket[i - 1];
}
for (i = n - 1; i >= 0; i--) {b[--bucket[(a[i] / exp) % BASE]] = a[i];
}
for (i = 0; i < n; i++) {a[i] = b[i];
}
exp *= BASE;
ifdef SHOWPASS
printf("\nPASS :");
print(a, n);
endif
}
}
int main() {
int arr[MAX];
int i, n;
printf(“Enter total elements (n <= %d) : “, MAX);
scanf(“%d”, &n);
n = n < MAX ? n : MAX;
printf(“Enter %d Elements : “, n);
for (i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
printf(“\nARRAY : “);
print(&arr[0], n);
radixsort(&arr[0], n);
printf(“\nSORTED : “);
print(&arr[0], n);
printf(“\n”);
return 0;
}
Lua
实例
— 获取表中位数
local maxBit = function (tt)
local weight = 10; -- 十進制
local bit = 1;
for k, v in pairs(tt) do
while v >= weight do
weight = weight * 10;
bit = bit + 1;
end
end
return bit;
end
— 基数排序
local radixSort = function (tt)
local maxbit = maxBit(tt);
local bucket = {};
local temp = {};
local radix = 1;
for i = 1, maxbit do
for j = 1, 10 do
bucket[j] = 0; --- 清空桶
end
for k, v in pairs(tt) do
local remainder = math.floor((v / radix)) % 10 + 1;
bucket[remainder] = bucket[remainder] + 1; -- 每個桶數量自動减少 1
end
for j = 2, 10 do
bucket[j] = bucket[j - 1] + bucket[j]; -- 每个桶的数量 = 以前桶数量和 + 自个数量
end
-- 按照桶的地位,排序 -- 这个是桶式排序,必须使用倒序,因为排序方法是从小到大,次序下来,会出现大的在小的下面清空。for k = #tt, 1, -1 do
local remainder = math.floor((tt[k] / radix)) % 10 + 1;
temp[bucket[remainder]] = tt[k];
bucket[remainder] = bucket[remainder] - 1;
end
for k, v in pairs(temp) do
tt[k] = v;
end
radix = radix * 10;
end
end;