在Javascript

时间:2016-11-19 10:52:22

标签: javascript sorting

我有一个函数urlScores,它以

的形式返回一个对象数组
[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]

我被要求根据分数使用冒泡排序对此数组进行排序。

我尝试做的是创建一个冒泡排序函数,该函数从urlScores返回对象并对其进行排序。

function sort(object)
{
  for(var i=  0; i < object.length; i++){
    if (object[i].score > object[i+1].score) {
      var temp = object[i]
      object[i]=object[i+1]
      object[i+1]=temp
    }
  }
}

应该调用的用于排序数组的函数如下:

function rankedScores(web,pattern)
{
  return (sort(urlScores(web,pattern)))
}

这似乎不起作用,我面临TypeError: object[(i + 1)] is undefined

感谢任何帮助

2 个答案:

答案 0 :(得分:0)

我已经纠正了你的排序功能。

function sort(a) {
    for (var i = 0; i < a.length - 1; i++) {
        if (a[i].score > a[i + 1].score) {
            var temp = a[i]
            a[i] = a[i + 1]
            a[i + 1] = temp
        }
    }
    return a;
}

这是一个例子

var arr= '[{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}]';

console.log(sort(arr));

答案 1 :(得分:0)

&#13;
&#13;
    var a = [{"url":"facebook","score":2},{"url":"reddit","score":1},{"url":"stackoverflow","score":3}];
 
function bubbleSort(a)
{
    var swapped;
    do {
        swapped = false;
        for (var i=0; i < a.length-1; i++) {
            if (a[i].score > a[i+1].score) {
                var temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}
 
bubbleSort(a);
console.log(a);
&#13;
&#13;
&#13;