Radix sort using bitwise operations

百般思念 提交于 2019-12-03 04:07:40

First of all, you don't need to convert an integer to bits, because it already is stored as bits. An int is usually 4 bytes, so 32 bits. You can access the bits using bit operators.

Radix sort is shown here in detail. https://en.wikipedia.org/wiki/Radix_sort

This example sorts based on base 10 digits.

To sort based on bit, you would change the algorithm slightly to use 2 instead of 10 in all places:

void radixsort(int *a, int n) {
...
  while (m / exp > 0) {
    int bucket[2] = { 0 };
    for (i = 0; i < n; i++)      bucket[a[i] / exp % 2]++;
    bucket[1] += bucket[0];
    for (i = n - 1; i >= 0; i--) b[--bucket[a[i] / exp % 2]] = a[i];
    for (i = 0; i < n; i++)      a[i] = b[i];
    exp *= 2;
...
  }
}

But if you needed to use bit wise operators instead, you could recognize that anything divided by 2 is simply >> 1, multiply by 2 is << 1, and modulo 2 is &1. By replacing exp with the bit position, we can rewrite as follows:

void radixsort(int *a, int n) {
  int i, b[MAX], m = a[0], bit = 0;
  for (i = 0; i < n; i++) if (a[i] > m) m = a[i];

  while ((m>>bit) > 0) {
    int bucket[2] = { 0 };
    for (i = 0; i < n; i++)      bucket[(a[i]>>bit) & 1]++;
    bucket[1] += bucket[0];
    for (i = n - 1; i >= 0; i--) b[--bucket[(a[i]>>bit) & 1]] = a[i];
    for (i = 0; i < n; i++)      a[i] = b[i];
    bit++;
...
  }
}

This sorts using a single bit. To use multiple bits, you'd need to make it more generic:

#define BITS 2
void radixsort(int *a, int n) {
  int i, b[MAX], m = a[0], pos = 0;
  int buckets=1<<BITS;
  int mask=buckets-1;
  for (i = 0; i < n; i++) if (a[i] > m) m = a[i];

  while ((m>>(pos*BITS)) > 0) {
    int bucket[1<<BITS] = { 0 };
    for (i = 0; i < n; i++)       bucket[(a[i]>>(pos*BITS)) & mask]++;
    for (i = 1; i < buckets; i++) bucket[i] += bucket[i - 1];
    for (i = n - 1; i >= 0; i--)  b[--bucket[(a[i]>>(pos*BITS)) & mask]] = a[i];
    for (i = 0; i < n; i++)       a[i] = b[i];
    pos++;
...
  }
}

This sorts using two bits, so 4 buckets are used for 00, 01, 10, and 11. 3 bits would use 8 buckets (000, 001, 010, 011, 100, 101, 110, 111).

You can see how increasing the BITS will make fewer passes, but the work done in each pass is larger.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!