为什么这个冒泡排序不起作用
Why is this bubblesort not working
我需要按包含的元组的第二个元素对以下数组进行排序。该过程贯穿始终,直到最后一个元素通过。之后我得到异常
ERROR TypeError: Cannot read property '1' of undefined
这是我使用的代码:
public list:Array<[string, number]> = new Array<[string, number]>();
//{["A", 0],["B", 8], ...}
...
var sorted = false
while (!sorted){
sorted = true;
this.list.forEach(function (element, index, array){
alert(element);
if (element[1] > array[index+1][1] ) {
array[index][1] = array[index+1][1];
array[index+1] = element;
sorted = false;
}
});
}
我不明白,为什么这不起作用
这一行:
array[index+1][1];
原因
ERROR TypeError: Cannot read property '1' of undefined
那是因为当迭代到达最后一个索引时,例如 5
,它试图从数组中取出 6
,这显然不存在。所以你需要在迭代时跳过最后一个索引,例如:
if(array.length - 1 === index)
return;
我会怎么做:
var sorted = false;
while(!sorted){
sorted = true;
for(let index = 1; index < array.length; index++) {
if(array[index][1] < array[index - 1][1]) {
([array[index], array[index - 1]] = [array[index - 1], array[index]]);
sorted = false;
}
}
或更简单:
array.sort((a, b) => a[1] - b[1])
我需要按包含的元组的第二个元素对以下数组进行排序。该过程贯穿始终,直到最后一个元素通过。之后我得到异常
ERROR TypeError: Cannot read property '1' of undefined
这是我使用的代码:
public list:Array<[string, number]> = new Array<[string, number]>();
//{["A", 0],["B", 8], ...}
...
var sorted = false
while (!sorted){
sorted = true;
this.list.forEach(function (element, index, array){
alert(element);
if (element[1] > array[index+1][1] ) {
array[index][1] = array[index+1][1];
array[index+1] = element;
sorted = false;
}
});
}
我不明白,为什么这不起作用
这一行:
array[index+1][1];
原因
ERROR TypeError: Cannot read property '1' of undefined
那是因为当迭代到达最后一个索引时,例如 5
,它试图从数组中取出 6
,这显然不存在。所以你需要在迭代时跳过最后一个索引,例如:
if(array.length - 1 === index)
return;
我会怎么做:
var sorted = false;
while(!sorted){
sorted = true;
for(let index = 1; index < array.length; index++) {
if(array[index][1] < array[index - 1][1]) {
([array[index], array[index - 1]] = [array[index - 1], array[index]]);
sorted = false;
}
}
或更简单:
array.sort((a, b) => a[1] - b[1])