--------------------------------------------------- | Date: 2003-05-28 16:08:17 | | Filename: bubble_sort.js | | Author: detour@metalshell.com | | | | http://www.metalshell.com/ | --------------------------------------------------- <!-- bubble_sort.js by detour@metalshell.com --> <!-- Generate 100 random numbers the use bubble sort to --> <!-- put them in ascending order. --> <!-- http://www.metalshell.com/ --> <html> <head> <title>JavaScript Random Number Generator.</title> </head> <body> <script type="text/javascript"> var ranarray = new Array(100); // Generate random numbers to fill ranarray. function genNumbers(listbox) { var i; for(i = 0; i < ranarray.length; i++) { ranarray[i] = Math.random()*100; // Round to nearest integer. ranarray[i] = Math.round(ranarray[i]); } // Update the select box list. updateList(listbox); } function sortNumbers(listbox) { var x, y, holder; // The Bubble Sort method. for(x = 0; x < ranarray.length; x++) { for(y = 0; y < (ranarray.length-1); y++) { if(ranarray[y] > ranarray[y+1]) { holder = ranarray[y+1]; ranarray[y+1] = ranarray[y]; ranarray[y] = holder; } } } // Update the select box list. updateList(listbox); } // Assign values in array to values in the select box. function updateList(listbox) { var i; for(i = 0; i < ranarray.length; i++) { if(listbox.options[i] == null) { listbox.options[i] = new Option(ranarray[i]); } else { listbox.options[i].text = ranarray[i]; } } } </script> <form> <select name="ranlist" size="20" style="width:200px"> </select><br><br> <input type="button" value="Generate Numbers" onclick="genNumbers(this.form.ranlist);"> <input type="button" value="Bubble Sort Numbers" onclick="sortNumbers(this.form.ranlist);"> </form> </body> </html>