Discuss / JavaScript / 数列排序和冒泡排序

数列排序和冒泡排序

Topic source

王闪_Frank

#1 Created at ... [Delete] [Delete and Lock User]

``````    var js = document.getElementById('test-list');
var arr = [];
//找到所有的list，然后排序
for( var i=0; i<js.children.length; i++ ){
arr.push(js.children[i].innerText);
}
arr.sort();
//因为style什么的都一样，所以只修改innerText值
for (var i = 0; i < js.children.length; i++) {
js.children[i].innerText = arr[i];
}
``````

``````     //冒泡排序，比较1/2-1/3-1/4-2/3-2/4-3/4......
//字符小的文字和大的比较，大的那个插到前面来
for (var i = 0; i < js.children.length - 1; i++ ) {
for (var j = i + 1; j < js.children.length; j++ ) {
// console.log(i);
// console.log(j);
if (js.children[i].innerText > js.children[j].innerText) {
console.log(i, j);
console.log(js.children[i].innerText, js.children[j].innerText);
js.insertBefore(js.children[j], js.children[i]);
}
}
}
``````

王闪_Frank

#2 Created at ... [Delete] [Delete and Lock User]

L0standfound

#3 Created at ... [Delete] [Delete and Lock User]

LevonLin

#4 Created at ... [Delete] [Delete and Lock User]

@L0standfound： `j = i + 1`决定比较区间的起点，因为不会自己跟自己比，所以从i+1开始啊； `children.length - 1`免去最后一次比较，因为最小的都冒泡到前面去了，最后一个一定是最大的。

• 1