重构
This commit is contained in:
@@ -1,57 +0,0 @@
|
||||
#ifndef INCLUDED_C_KNUTHSHUFFLE_H
|
||||
#define INCLUDED_C_KNUTHSHUFFLE_H
|
||||
|
||||
#ifndef INCLUDED_C_MEMORY_H
|
||||
#include <c_Memory.h>
|
||||
#endif /*INCLUDED_C_MEMORY_H*/
|
||||
|
||||
|
||||
#ifndef INCLUDED_STDLIB_H
|
||||
#define INCLUDED_STDLIB_H
|
||||
#include <stdlib.h>
|
||||
#endif /*INCLUDED_STDLIB_H*/
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------------------------------------------------------ */
|
||||
/* */
|
||||
|
||||
/**
|
||||
* 通用 Knuth 洗牌演算法
|
||||
* @param base 指向待打亂陣列首元素的指標
|
||||
* @param num 陣列中元素的個數
|
||||
* @param size 每個元素的大小(位元組數)
|
||||
*/
|
||||
C_STATIC_FORCE_INLINE
|
||||
void c_KnuthShuffle(void* base, c_size_t num, c_size_t size) {
|
||||
if (base == NULL || num < 2 || size == 0) return;
|
||||
|
||||
char* arr = (char*)base;
|
||||
|
||||
// 使用棧快取 buffer 進行記憶體交換,避免堆分配開銷
|
||||
#define SHUFFLE_STACK_LIMIT 128
|
||||
char stack_buf[SHUFFLE_STACK_LIMIT];
|
||||
void* temp = (size <= SHUFFLE_STACK_LIMIT) ? stack_buf : C_ALLOC(size);
|
||||
if (temp == NULL) return;
|
||||
|
||||
// 從後往前遍歷陣列
|
||||
for (c_int_t i = num - 1; i > 0; i--) {
|
||||
// 生成一個 0 到 i 之間(包含 i)的隨機索引
|
||||
c_int_t j = rand() % (i + 1);
|
||||
|
||||
// 交換 arr[i] 和 arr[j]
|
||||
if (i != j) {
|
||||
char* a = arr + (i * size);
|
||||
char* b = arr + (j * size);
|
||||
memcpy(temp, a, size);
|
||||
memcpy(a, b, size);
|
||||
memcpy(b, temp, size);
|
||||
}
|
||||
}
|
||||
|
||||
if (size > SHUFFLE_STACK_LIMIT) {
|
||||
C_FREE(temp);
|
||||
}
|
||||
#undef SHUFFLE_STACK_LIMIT
|
||||
}
|
||||
|
||||
#endif /*INCLUDED_C_KNUTHSHUFFLE_H*/
|
||||
Reference in New Issue
Block a user