我的气泡排序仅适用于Maggie下表格第二列中的最高编号。而且它不能遍及整个数组。什么在我的代码中不起作用?我查看了不同的冒泡排序代码,它看起来与我的类似。
function main() {
var myArr = new Array(
["Robert Hill", 123.54],
["Christopher Reddkin", 54.67],
["Maggie Woods", 1000.87],
["Jennifer Jones", 3.34],
["Marcus Parker", 64.98]);
original(myArr);
bubbleSort(myArr);
}
function original(myarray) {
for (var i = 0; i < 2; i++) {
myarray[i];
for (var j = 0; j < 2; j++) {
myarray[i][j];
}
}
var table = document.getElementById("myTable");
for (var i = 0, row; row = table.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.innerText = myarray[i][j];
}
}
console.log(myarray);
return myarray;
}
function bubbleSort(myarr) {
var lengths = myarr.length;
for (var i = 0; i < lengths; i++) {
for (var j = 0; j < (lengths - i - 1); j++) {
if (myarr[i] > myarr[j + 1]) {
var tmp = myarr[j];
myarr[j] = myarr[j + 1];
myarr[j + 1] = tmp;
}
}
}
var table2 = document.getElementById("myTable2");
for (var i = 0, row; row = table2.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.innerText = myarr[i][j];
}
}
console.log(myarr);
return myarr;
}
main();
td { border: 1px solid black; }
table { margin: 1em; border-collapse: collapse; }
<table id="myTable">
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
<table id="myTable2">
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
<tr><td></td><td></td></tr>
</table>
答案 0 :(得分:0)
我稍微修改了您的逻辑。如果下一个更大,只需交换阵列单元即可。
function bubbleSort(myarr) {
var lengths = myarr.length;
for (var i = 0; i < lengths; i++) {
for (var j = i+1; j < (lengths); j++) {
if (myarr[j][1] > myarr[i][1]) {
var tmp = myarr[i];
myarr[i] = myarr[j];
myarr[j] = tmp;
}
}
console.log(myarr);
console.log("-------------------");
}
var table2 = document.getElementById("myTable2");
for (var i = 0, row; row = table2.rows[i]; i++) {
for (var j = 0, col; col = row.cells[j]; j++) {
col.innerText = myarr[i][j];
}
}
console.log(myarr);
return myarr;
}