1

I have a large list of positive integers in an array and would like to use a bead sort but have found in to be not well documented. does anyone have the code for a bead sort?

learner123
  • 961
  • 1
  • 10
  • 16

2 Answers2

2

This page has implementations in several languages, including C: http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort

Graham Clark
  • 12,886
  • 8
  • 50
  • 82
0

From This Question, comes a modification of Bead Sort that uses O(N) extra space instead of O(N*k) as in the Rosetta Code version.

void sort(int A[], int N)
{
    int i, j;
    int *R = calloc(N, sizeof(int));

    do for (i = j = 0; i < N; i++) 
      if (A[i]) { R[j++]++; A[i]--; }
    while (j);

    for (j = N, i = 0; i < N; i++)
      A[i] = R[--j]; // A is now sorted ascending.

    free(R);
}

However, it is at least 10x slower than qsort, and it gets worse the larger your array elements get. I wouldn't recommend using it.

Community
  • 1
  • 1
AShelly
  • 34,686
  • 15
  • 91
  • 152