javascript冒泡法排序算法演示代码
<html> <head> <script type="text/javascript"> // GLOBAL FUNCTION Array.prototype.bubble_sort = function() { var i, j; var swapped; var newarray = this.slice(0); var swap = function(j, k) { var temp = newarray[j]; newarray[j] = newarray[k]; newarray[k] = temp; return(true); } for(i=1; i<newarray.length; i++) { swapped = false; for(j=0; j<newarray.length - i; j++) { if (newarray[j+1] < newarray[j]) { swapped = swap(j, j+1); } } if (!swapped) break; } return(newarray) } // LOCAL FUNCTION show = function (inarray, title) { document.writeln("<h4>"+title+":</h4>"); document.writeln(inarray.join(", ")+"<br />"); } </script> </head> <body> <script> // MAIN // test bubble_sort function sorted_array = [1, 4, 7, 2, 1, 3, 2, 1, 4, 2, 3, 2, 1].bubble_sort(); show(sorted_array, "Sorted Array"); // result: [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 7] </script> </body> </html>