我想了解基數排序如何處理按位,所以我在互聯網上找到了這個算法,但我不明白它是如何工作的!C++基數排序按位運算
#include <algorithm>
#include <iostream>
#include <iterator>
// Radix sort comparator for 32-bit two's complement integers
class radix_test
{
const int bit; // bit position [0..31] to examine
public:
radix_test(int offset) : bit(offset) {} // constructor
bool operator()(int value) const // function call operator
{
if (bit == 31) // sign bit
return value < 0; // negative int to left partition
else
return !(value & (1 << bit)); // 0 bit to left partition
}
};
// Least significant digit radix sort
void lsd_radix_sort(int *first, int *last)
{
for (int lsb = 0; lsb < 32; ++lsb) // least-significant-bit
{
std::stable_partition(first, last, radix_test(lsb));
}
}
// Most significant digit radix sort (recursive)
void msd_radix_sort(int *first, int *last, int msb = 31)
{
if (first != last && msb >= 0)
{
int *mid = std::partition(first, last, radix_test(msb));
msb--; // decrement most-significant-bit
msd_radix_sort(first, mid, msb); // sort left partition
msd_radix_sort(mid, last, msb); // sort right partition
}
}
// test radix_sort
int main()
{
int data[] = { 170, 45, 75, -90, -802, 24, 2, 66 };
lsd_radix_sort(data, data + 8);
// msd_radix_sort(data, data + 8);
std::copy(data, data + 8, std::ostream_iterator<int>(std::cout, " "));
return 0;
}
任何人都可以請解釋這個工作如何排序整數! 非常感謝
不要試圖從代碼學習算法,這太難了,你最終會學習錯誤的東西。從一本書或網頁或人員學習。 https://en.wikipedia.org/wiki/Radix_sort –
我有一個關於使用按位基數算法的想法,但我想了解它如何使用這種算法,並在維基百科他們不談論按位運算 – satyres
哦,我誤解,並認爲你正在嘗試學習基數種類。對不起 –