Wu Yuxiong - born natural data structure: Ten classic sort algorithm - Radix Sort

Radix Sort
Radix sort comparison type is a non-integer sorting algorithm, the principle is the integer number of bits is cut by different numbers, then the number of bits for each were compared. Since the integer can be expressed floating-point strings (such as name or date) and a specific format, the radix sort is not only used for integer.

1 . Radix Sort Sort count vs vs bucket sort
Radix sort in two ways:

These three sorting algorithms make use of the concept of the barrel, but there are obvious differences in the use of barrel:

Radix sort: to allocate bucket based on each digital keys;
Counting sequencing: each bucket storing only a single key;
Bucket sort: storing each bucket value of a range;
Code
JavaScript
//LSD Radix Sort
was counter = [];
function radixSort(arr, maxDigit) {
    was v = 10 ;
    var dev = 1;
    for (var i = 0; i < maxDigit; i++, dev *= 10, mod *= 10) {
        for(var j = 0; j < arr.length; j++) {
            var bucket = parseInt((arr[j] % mod) / dev);
            if(counter[bucket]==null) {
                counter[bucket] = [];
            }
            counter[bucket].push(arr[j]);
        }
        var pos = 0;
        for(var j = 0; j < counter.length; j++) {
            var value = null;
            if(counter[j]!=null) {
                while ((value = counter[j].shift()) != null) {
                      arr[pos++] = value;
                }
          }
        }
    }
    return arr;
}
Java
/**
 * Radix sort
  * may also consider the case of a negative reference: https://code.i-harness.com/zh-CN/q/ e98fa9
  * / 
public class RadixSort the implements IArraySort {

    @Override
    public int[] sort(int[] sourceArray) throws Exception {
        // to arr copy, does not change the parameter content
        int[] arr = Arrays.copyOf(sourceArray, sourceArray.length);

        int maxDigit = getMaxDigit(arr);
        return radixSort(arr, maxDigit);
    }

    /**
     * Obtain the highest median
      * /
    private int getMaxDigit(int[] arr) {
        int maxValue = getMaxValue(arr);
        return getNumLenght(maxValue);
    }

    private int getMaxValue(int[] arr) {
        int maxValue = arr[0];
        for (int value : arr) {
            if (maxValue < value) {
                maxValue = value;
            }
        }
        return maxValue;
    }

    protected int getNumLenght(long num) {
        if (num == 0) {
            return 1;
        }
        int lenght = 0;
        for (long temp = num; temp != 0; temp /= 10) {
            lenght++;
        }
        return lenght;
    }

    private int[] radixSort(int[] arr, int maxDigit) {
        int mod = 10;
        int dev = 1;

        for (int I = 0; I <maxDigit; I ++, dev * = 10, 10 = MOD * ) {
             // consider a negative number, where the number of extended double queue, wherein [0-9] corresponding to negative, [10- 19] corresponding to the positive (+ bucket 10 )
            int[][] counter = new int[mod * 2][0];

            for (int j = 0; j < arr.length; j++) {
                int bucket = ((arr[j] % mod) / dev) + mod;
                counter[bucket] = arrayAppend(counter[bucket], arr[j]);
            }

            int pos = 0;
            for (int[] bucket : counter) {
                for (int value : bucket) {
                    arr[pos++] = value;
                }
            }
        }

        return arr;
    }

    /**
     * Automatic expansion, and save the data
      *
     * @param arr
     * @param value
     */
    private int[] arrayAppend(int[] arr, int value) {
        arr = Arrays.copyOf(arr, arr.length + 1);
        arr[arr.length - 1] = value;
        return arr;
    }
}
PHP
function radixSort($arr, $maxDigit = null)
{
    if ($maxDigit === null) {
        $maxDigit = max($arr);
    }
    $counter = [];
    for ($i = 0; $i < $maxDigit; $i++) {
        for ($j = 0; $j < count($arr); $j++) {
            preg_match_all('/\d/', (string) $arr[$j], $matches);
            $numArr = $matches[0];
            $lenTmp = count($numArr);
            $bucket = array_key_exists($lenTmp - $i - 1, $numArr)
                ? intval($numArr[$lenTmp - $i - 1])
                : 0;
            if (!array_key_exists($bucket, $counter)) {
                $counter[$bucket] = [];
            }
            $counter[$bucket][] = $arr[$j];
        }
        $pos = 0;
        for ($j = 0; $j < count($counter); $j++) {
            $value = null;
            if ($counter[$j] !== null) {
                while (($value = array_shift($counter[$j])) !== null) {
                    $arr[$pos++] = $value;
                }
          }
        }
    }

    return $arr;
}
++ C 
int maxbit (int Data [], int n-) // helper function, seeking maximum number of bits of data
{
    MAXDATA int = Data [0]; /// < the maximum number of
     /// to find the maximum number, and then seek the number of bits, so that each turn has a number of previously determined number of bits, little optimization points.
    for (int I =. 1; I <n-; ++ I)
    {
        if (maxData < data[i])
            maxData = data[i];
    }
    int d = 1;
    int p = 10;
    while (maxData >= p)
    {
        //p *= 10; // Maybe overflow
        maxData /= 10;
        ++d;
    }
    return D;
 / * D = int. 1; // save the maximum number of bits
    int p = 10;
    for(int i = 0; i < n; ++i)
    {
        while(data[i] >= p)
        {
            p *= 10;
            ++d;
        }
    }
    return d;*/
}
radixsort void (int Data [], int n-) // radix sorting
{
    int d = maxbit(data, n);
    int *tmp = new int[n];
    int * COUNT = new new int [10]; // counter
    int i, j, k;
    the radix int =. 1 ;
     for (I =. 1; I <= d; I ++) // for Scheduling in d
    {
        for(j = 0; j < 10; j++)
            COUNT [J] = 0; // each dispensing emptied before counter
         for (J = 0; J <n-; J ++ )
        {
            K = (Data [J] / the radix) 10%; // record the number of statistics for each bucket
            count[k]++;
        }
        for(j = 1; j < 10; j++)
            COUNT [J] = COUNT [J -. 1] + COUNT [J]; // the tmp sequentially allocated to each position in the tub
         for (n-J = -. 1; J> = 0; J,) // will All records in the bucket in order to collect tmp
        {
            k = (data[j] / radix) % 10;
            tmp[count[k] - 1] = data[j];
            count[k]--;
        }
        for (J = 0; J <n-; J ++) // copy the contents of the data in the temporary array
            data[j] = tmp[j];
        radix = radix * 10;
    }
    delete []tmp;
    delete []count;
}
C
#include<stdio.h>
#define MAX 20
//#define SHOWPASS
#define BASE 10

void print(int *a, int n) {
  int i;
  for (i = 0; i < n; i++) {
    printf("%d\t", a[i]);
  }
}

void radixsort(int *a, int n) {
  int i, b[MAX], m = a[0], exp = 1;

  for (i = 1; i < n; i++) {
    if (a[i] > m) {
      m = a[i];
    }
  }

  while (m / exp > 0) {
    int bucket[BASE] = { 0 };

    for (i = 0; i < n; i++) {
      bucket[(a[i] / exp) % BASE]++;
    }

    for (i = 1; i < BASE; i++) {
      bucket[i] += bucket[i - 1];
    }

    for (i = n - 1; i >= 0; i--) {
      b[--bucket[(a[i] / exp) % BASE]] = a[i];
    }

    for (i = 0; i < n; i++) {
      a[i] = b[i];
    }

    exp *= BASE;

#ifdef SHOWPASS
    printf("\nPASS   : ");
    print(a, n);
#endif
  }
}

int main () {
  int arr[MAX];
  int i, n;

  printf("Enter total elements (n <= %d) : ", MAX);
  scanf("%d", &n);
  n = n < MAX ? n : MAX;

  printf("Enter %d Elements : ", n);
  for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
  }

  printf("\nARRAY  : ");
  print(&arr[0], n);

  radixsort(&arr[0], n);

  printf("\nSORTED : ");
  print(&arr[0], n);
  printf("\n");

  return 0;
}
Lua
 - get the median table
local maxBit = function (tt)
    weight local = 10; - Decimal
    local bit = 1;
   
    for k, v in pairs(tt) do
        while v >= weight do
            weight = weight * 10;
            bit = bit + 1;  
        end
    end
    return bit;
end
- Radix Sort
local radixSort = function (tt)
    local maxbit = maxBit(tt);

    local bucket = {};
    local temp = {};
    local radix = 1;
    for i = 1, maxbit do
        for j = 1, 10 do
            bucket [J] = 0; --- empty tub
        end
        for k, v in pairs(tt) do
            local remainder = math.floor((v / radix)) % 10 + 1;    
            bucket [REMAINDER] = bucket [REMAINDER] + 1; - automatically increase the number of buckets per 1
        end
       
        for j = 2, 10 do
            bucket [J] = bucket [J -. 1] + bucket [J]; - number = number of previous buckets per bucket and + from a number of
        end
        - in accordance with the position of the bucket, the sort - this is a bucket sort, you must use the reverse, because the sorting method is small to large, the order down, there will be a big top in a small empty.
        for K = # TT,. 1, -1 do 
            local Math.floor REMAINDER = ((TT [K] / the radix)) 10% +. 1 ;
            temp[bucket[remainder]] = tt[k];
            bucket[remainder] = bucket[remainder] - 1;
        end
        for k, v in pairs(temp) do
            tt [k] = v;
        end
        radix = radix * 10;
    end
end;

 

Guess you like

Origin www.cnblogs.com/tszr/p/11973857.html