|
|
| Beyond HTML Goodies (ISBN: 0789727803) |
 |
List Price: $24.99
Our Price: $17.49
Used Price: $16.84
Release Date: 27 June, 2002
Manufacturer: Que (Paperback)
Sales Rank: 36,474
Author: Joe Burns, INT Media Group
|
More Info
|
|
|
Javascript Bubble Sort
|
2003-05-28 16:08:17
|
| |
html
|
|
|
|
|
Category: source:html:javascript
|
|
Description: Generate 100 random numbers the use bubble sort to put them in ascending order.
|
|
Platform: all
|
|
Author: detour
|
|
Viewed: 16412
|
|
Rating: 3.9/5 (65 votes)
|
|
|
| If you have any questions about
this piece of code or still need help, try posting your question on the forum. |
<!-- 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>
|
|
|