Elbert Bae
Elbert Bae

Reputation: 231

Sorting an array without arr.sort() method, what's going on here?

I believe I've figured this out, but wanted some insight as to how this is working in reality. I have this function here that sorts numbers in ascending order. My understanding is that loops going past the array length returns undefined and had it initially written as such below.

However, it appears that the last number in the array (6) does not get reached and the function leaves that number behind. Arr.length - 1 should be an index of 5 meaning that arr[5] gets called at some point, but it doesn't seem to be the case?

In the function below the first one, I took out arr.length - 1 and simply put arr.length and it appears to work correctly, but arr.length = 6 in this case. My understanding is list[6] does not exist or would be undefined in this case, so can someone help me understand why the second function works and not the first for sorting?

Thanks!

// this one doesn't work
let list = [1, 10, 9, 8, 3, 6];
function sortNumbers(arr) {
    for (let i = 1; i < arr.length - 1; i++) {
        for (let j = 0; j < arr.length - 1; j++) {
            console.log(arr[i]);
            let temp = arr[i];
            if (arr[i] < arr[j]) {
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}


// this one works?
let list = [1, 10, 9, 8, 3, 6];
function sortNumbers(arr) {
    for (let i = 1; i < arr.length; i++) {
        for (let j = 0; j < arr.length; j++) {
            console.log(arr[i]);
            let temp = arr[i];
            if (arr[i] < arr[j]) {
                arr[i] = arr[j];
                arr[j] = temp;
            }
        }
    }
    return arr;
}

Upvotes: 0

Views: 2438

Answers (3)

Akhil Singh
Akhil Singh

Reputation: 730

arr.length = 6, and your loop is (i < arr.length - 1) means i value is 0 to (6-1=5). it means i until i is less than 5. if you use less than equal to (<=) operator then your problem resolve.it means loop is value of i is less than or equal to 5. the array index start from 0 to n-1 so value is (i=0 ; i<=n-1;i++).

Upvotes: 0

Garrett Wesley
Garrett Wesley

Reputation: 23

arr.length = 6, so the for loop must index the array from 0 until it is less than arr.length

Upvotes: 1

Hoggie Johnson
Hoggie Johnson

Reputation: 80

The first function does not work because the for loop condition is for (let j = 0; j < arr.length - 1; j++) here arr.length - 1 is equal to 5, so the for loop would go from 0 until it is less than (6 - 1) so it never actually reaches j=5.

The second function works because it goes from 0 until it is less than 6, so it does reach j=5

Upvotes: 0

Related Questions