Search code examples
javascriptbubble-sort

A customized swap fails in bubbleSort


I wrote such a swap function for bubbleSort:

function swap(a, b) {
    tmp = a;
    a = b;
    b = tmp;
}

then encapsulate it in the bubbleSort:

function bubbleSort(arr) {
    let len = arr.length;
    for (let i = 0; i < len; i++) {
        for (let j = 0; j < len - 1; j++) {
            // swap the elements
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]); // use swap here.
            }
        }
    }
}

And test it with:

arr = [34, 87, 21, 0, -11];
bubbleSort(arr)

but it stay unchanged, what's the problem?


Solution

  • The swap function takes a copy of the number instead of the pointer.. welcome to javascript?
    Either way, you would need the array and the indexes to do a swap because objects are pointers, numbers are not
    Here's an example

    //working swap function
    function swap(arr, a, b){
      var tmp=arr[a]
      arr[a]=b
      arr[b]=tmp
    }
    
    function bubbleSort(arr) {
        let len = arr.length;
        for (let i = 0; i < len; i++) {
            for (let j = 0; j < len - 1; j++) {
                // swap the elements
                if (arr[j] > arr[j + 1]) {
                    swap(arr, j, j+1); // use swap here.
                }
            }
        }
        return arr //because why not
    }
    
    arr = [34, 87, 21, 0, -11];
    console.log(bubbleSort(arr))