原理:是临近的数字两两进行比较,按照从小到大或者从大到小的顺序进行交换,
function bubbleClick() { var str = "50,1,4,6,9,76,43,22,2,44,7,66"; bubble(str); } function bubble(str) { var a = new Array(); a = str.split(‘,‘);//字符串数组, //var a = [50, 1, 4, 6, 9, 76, 43, 22, 2, 44, 7, 66] var tmp = 0; for (var i = 0; i < a.length; i++) { for (var j = 0; j < a.length - i - 1; j++) { //两个相邻的比较大小,把小的留下, if (a[j] > a[j + 1]) { tmp = a[j + 1]; a[j + 1] = a[j]; a[j] = tmp; } } } console.log(a); }
时间: 2024-10-10 12:39:22