Saturday, November 21, 2015

Radix Sort in JavaScript

This program will show you how to implement Radix Sort algorithm using JavaScript programming language.

If you  have some questions please send me an email at jake.r.pomperada@gmail.com and jakerpomperada@yahoo.com

My mobile number here in the Philippines is 09173084360.



Sample Program Output



Program Listing

<html>
 <head>
   <title>Radix Sort</title>
  </head>
<body> 
   <script>

   var values=[],a=[];
   var temp=0,pos=0;
   
   document.write("<font face='arial' size='4'>RADIX SORT </font>");
   document.write("<br><br>");
 for (a=0; a<10; a++) {
  values.push(Number(prompt("Enter item value at no. " + (a+1))));
   }
      document.write("<font face='arial' size='4'>Numbers");
     document.write(" given by the user </font>");
     document.write("<br><br>");
  for (a=0;a<10; a++) {
    document.write("<font face='arial' size='4'> " +values[a] + "");
   }

function radix_sort (A) {
var k = Math.max.apply(null, A.map(function(i) {
    return Math.ceil(Math.log(i)/Math.log(2));
}));

for (var d = 0; d < k; ++d) {
    for (var i = 0, p = 0, b = 1 << d, n = A.length; i < n; ++i) {
        var o = A[i];
        if ((o & b) == 0) {
            A.splice(p++, 0, A.splice(i, 1)[0]);
       }
   }
}
return A;
}

      radix_sort(values);

      document.write("<br><br>");
 document.write("<font face='arial' size='4'>Sorted List of Numbers </font>");
 document.write("<br><br>");
 
  for (a=0; a<10; a++) {
    document.write("<font face='arial' size='4'> " +  values[a]+"</font>");
  }  
  </script>
  </body>
 </html>  
   


No comments:

Post a Comment