functionQueue () {//using the queue to simulate cardinality sorting the method in the corresponding queue constructor one cannot be less, or it will go wrong This. DataStore = []; This. Enqueue =Enqueue; This. dequeue =dequeue; This. Empty =empty; } functionEnqueue (Element) {//add an element to the end of the team This. Datastore.push (Element); } functionDequeue () {//remove elements from the first team return This. Datastore.shift (); } functionEmpty () {//determine if the queue is empty if( This. Datastore.length = = 0) { return true; } Else { return false; } } //simulating the operation of the box functionDistribute (nums, queues, n, digit) {//Actually, queues is a simulated box. for(vari = 0; I < n; ++i) {if(Digit = = 1) {Queues[nums[i]% 10].enqueue (Nums[i]); //because every bit of queues is a box, it can store multiple elements}Else{Queues[math.floor (nums[i]/10)].enqueue (Nums[i]); //Math.floor (x): maximum integer less than or equal to x } } } //store the data in the box into an array for easy reading functionCollect (queues, nums) {vari = 0; for(vardigit = 0; Digit < 10; ++Digit) { while(!Queues[digit].empty ()) { //Why should you judge non-empty? Because each element may contain more than one child element in the boxnums[i++] =Queues[digit].dequeue (); } } } functionDisparray (arr) {//to output a one-dimensional array for(vari = 0; i < arr.length; ++i) {document.write (Arr[i]+ " "); } } //Main program varQueues = []; for(vari = 0; I < 10; ++i) {queues[i]=NewQueue ();//each element of the queues is a queue } varNums = []; for(vari = 0; I < 10; ++i) {nums[i]= Math.floor (Math.random () * 101); //math.random (): Returns the number of random numbers between 0-1, which is greater than or equal to 0, less than 1} document.write ("Before radix sort:" + "<br/>"); Disparray (Nums); Distribute (Nums, queues,10, 1); Collect (queues, nums); Distribute (Nums, queues,10, 10); Collect (queues, nums); document.write ("<br/>" + "after radix sort:" + "<br/>"); Disparray (Nums); /*results of the above program operation: Before Radix sort:76--------45 6*/
About the principle: refer to the previous article: understanding of the principle of cardinal sorting
2016-04-10 18:47:32
Simulating cardinality sorting with a queue