Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript bubble sort of an array with objects

Tags:

javascript

beginner here!

Recently stumbled upon a problem. Basically, the program needs to sort an array of objects by one of their fields without actually using the sort function. I've tried this code using bubble sort algorithm, but it doesn't seem to be working:

var arrayOfPeople = [
    {name: "Rick", age: 30, place: 2},
    {name: "Alan", age: 25, place: 1},
    {name: "Joe", age: 40, place: 4},
    {name: "Dave", age: 35, place: 3}
];


function bubbleSort(a,par)
{
    var swapped;

    do {
        swapped = false;

        for (var i = 0; i < a.length - 1; i++) {
            if (a[i].par > a[i + 1].par) {
                var temp = a[i];

                a[i] = a[i + 1];
                a[i + 1] = temp;

                swapped = true;
            }
        }
    } while (swapped);
}


bubbleSort(arrayOfPeople,'age');

for (i = 0; i < arrayOfPeople.length; i++) {
    console.log(arrayOfPeople[i]);
}

My guess is that I'm doing something wrong syntax-wise. Will appreciate any feedback.

like image 373
nainy Avatar asked Dec 15 '22 10:12

nainy


2 Answers

The only problem was that you were not using the "par" argument correctly. The obj.prop syntax will always try to look for property named "prop" so to have it dynamic you need to use square brackets e.g. obj["prop"] which can get variable instead of "prop".

You didn't get any errors as a[i].par and a[i+1].par both returned undefined which can be compared to itself. (hence a[i].par > a[i+1].par always returns false)

Here is revised code that works:

function bubbleSort(a, par)
{
    var swapped;
    do {
        swapped = false;
        for (var i = 0; i < a.length - 1; i++) {
            if (a[i][par] > a[i + 1][par]) {
                var temp = a[i];
                a[i] = a[i + 1];
                a[i + 1] = temp;
                swapped = true;
            }
        }
    } while (swapped);
}


bubbleSort(arrayOfPeople, 'age');

for (i = 0; i < arrayOfPeople.length; i++) {
   console.log(arrayOfPeople[i]);
}

Live test case.

Worth to mention in this context, that the function changing the actual object (array in this case) is not a trivial thing. To learn more what is passed by value and what is passed by reference take a look in this excellent question: Is JavaScript a pass-by-reference or pass-by-value language?

like image 166
Shadow Wizard Hates Omicron Avatar answered Jan 15 '23 13:01

Shadow Wizard Hates Omicron


Use the built in array sort function:

arrayOfPeople.sort(function(a,b) {return a.age-b.age;});
like image 37
TheSavage Avatar answered Jan 15 '23 13:01

TheSavage