0

JavaScript で基数ソート アルゴリズムを実装するのに助けが必要です。

次のコードでこの例をオンラインで見つけましたが、そのサイトに合わせて調整されているように見えるため、関数を呼び出す方法がわかりません。

// Radix sort a (base 2)
// Numbers must be in the range 0 to 2**31 - 1
function radixSort() {
  readArray('i');
  var b0 = new obj();  // Bin for 0 digits
  var b1 = new obj();  // Bin for 1 digits

  for (var i=0; i<32; ++i) {
    if (form.step.checked) {  // Single step
      writeArray('i','a');

      if (!confirm("Sort on bit "+i))
        return;    
    }

    var mask = 1<<i;     // Digit (2**i)
    var biggest = 2<<i;  // If all of a is smaller, we're done
    var zeros=0;         // Number of elements in b0, b1
    var ones=0;
    var found=false;     // Any digits past i?

    for (var j=0; j<n; ++j) { // Sort into bins b0, b1
      if ((a[j] & mask) == 0)
        b0[zeros++] = a[j];
      else
        b1[ones++] = a[j];

      if (a[j]>=biggest)  // Any more digits to sort on?
        found=true;
    }

    for (j=0; j<zeros; ++j)  // Concatenate b0, b1 back to a
      a[j]=b0[j];

    for (j=0; j<ones; ++j)
      a[j+zeros]=b1[j];

    form.imoves.value = parseInt(form.imoves.value)+n;

    if (!found)
      break;
  }

  writeArray('i','a');
}
4

4 に答える 4

4

「基数ソート」という用語は扱いにくいものです。実際には、MSB (最上位ビット) 基数と LSB (最下位ビット) 基数の 2 つの異なる種類があります。(B が数字の D に置き換えられる場合があります)。ここに両方の​​実装があります。

MSB 基数:

//arguments to sort an array:
//arr: array to be sorted
//begin: 0
//end: length of array
//bit: maximum number of bits required to represent numbers in arr
function sort(arr, begin, end, bit)
{
  var i, j, mask;
  i = begin;
  j = end;
  mask = 1 << bit;
  while(i < j)
  {
    while(i < j && !(arr[i] & mask))
    {
      ++i;
    }
    while(i < j && (arr[j - 1] & mask))
    {
      --j;
    }
    if(i < j)
    {
      j--;
      var tmp = arr[i];
      arr[i] = arr[j];
      arr[j] = tmp;
      i++;
    }
  }
  if(bit && i > begin)
  {
    sort(arr, begin, i, bit - 1);
  }
  if(bit && i < end)
  {
    sort(arr, i, end, bit - 1);
  }
}
sort(arr, 0, arr.length, 32);  //Here I've assumed that the values in arr are integers that fit in 32 bits

LSB 基数:

function insert(arr, i, j)
{
  tmp = arr[i];
  arr.splice(i, 1);
  arr.splice(j, 0, tmp);
}

//arguments to sort an array:
//arr: array to be sorted
function sort(arr)
{
  var bit, end, i, mask;
  bit = 0;
  while(true) 
  {
    mask = 1 << bit;
    i = 0;
    end = arr.length;
    while(i < end)
    {
      if(arr[i] & mask)
      {
        insert(arr, i, arr.length - 1);
        end--;
      }
      else
      {
        i++;
      }
    }
    bit++;
    if(end === arr.length)
    {
      break;
    }
  }
}

これらのアルゴリズムをhttp://visualsort.appspot.com/から取り出しました。次に、それらをhttp://jashkenas.github.com/coffee-script/で javascript にコンパイルし、読みやすくするために insert method/reformatted を記述しました。

于 2011-10-29T07:04:05.017 に答える
0

私のバージョンはより冗長ですが、大規模なデータセットに対して非常に高速に実行されます。

      var testArray = [ 331, 454, 230, 34, 343, 45, 59, 453, 345, 231, 9 ];

  function radixBucketSort (arr) {
    var idx1, idx2, idx3, len1, len2, radix, radixKey;
    var radices = {}, buckets = {}, num, curr;
    var currLen, radixStr, currBucket;

    len1 = arr.length;
    len2 = 10;  // radix sort uses ten buckets

    // find the relevant radices to process for efficiency        
    for (idx1 = 0;idx1 < len1;idx1++) {
      radices[arr[idx1].toString().length] = 0;
    }

    // loop for each radix. For each radix we put all the items
    // in buckets, and then pull them out of the buckets.
    for (radix in radices) {          
      // put each array item in a bucket based on its radix value
      len1 = arr.length;
      for (idx1 = 0;idx1 < len1;idx1++) {
        curr = arr[idx1];
        // item length is used to find its current radix value
        currLen = curr.toString().length;
        // only put the item in a radix bucket if the item
        // key is as long as the radix
        if (currLen >= radix) {
          // radix starts from beginning of key, so need to
          // adjust to get redix values from start of stringified key
          radixKey = curr.toString()[currLen - radix];
          // create the bucket if it does not already exist
          if (!buckets.hasOwnProperty(radixKey)) {
            buckets[radixKey] = [];
          }
          // put the array value in the bucket
          buckets[radixKey].push(curr);          
        } else {
          if (!buckets.hasOwnProperty('0')) {
            buckets['0'] = [];
          }
          buckets['0'].push(curr);          
        }
      }
      // for current radix, items are in buckets, now put them
      // back in the array based on their buckets
      // this index moves us through the array as we insert items
      idx1 = 0;
      // go through all the buckets
      for (idx2 = 0;idx2 < len2;idx2++) {
        // only process buckets with items
        if (buckets[idx2] != null) {
          currBucket = buckets[idx2];
          // insert all bucket items into array
          len1 = currBucket.length;
          for (idx3 = 0;idx3 < len1;idx3++) {
            arr[idx1++] = currBucket[idx3];
          }
        }
      }
      buckets = {};
    }
  }
  radixBucketSort(testArray);
  console.dir(testArray);          
于 2016-08-16T16:23:22.810 に答える