Using native JS to write bubble sort and animation demonstration

Time:2021-2-24

Method 1 (user defined function)

Please click:Bubble sort animation demonstration(how many rows to traverse and how many times to swap each row)

/*Steps: 1. Declare named function (formal parameter array)
            2. For sets the outer loop to control how many times to traverse
            3. For sets the inner loop to control how many times to traverse the exchange
            4. If setting satisfies pairwise comparison condition, index number exchanges pairwise and temporary variables
            5. Return return value
            6. Variable storage = call function (array of arguments)
            7. Console print variable output*/

function bubble(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = 0; j < arr.length - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}
var arr = bubble([100, 26, 4, 13, 200, -21, 59]);
console.log(arr);  // [-21, 4, 13, 26, 59, 100, 200]

 

Method 2 (built in object)

function bubSort(newArr) {
    /*Note: the built-in object method sort() calls tostring() transformation, which compares strings
        Solution: sort() receives a comparison function compare to solve the number size comparison with the same string length*/
    function compare(value1, value2) {
        if (value1 < value2) {
            return -1;
        } else if (value1 > value2) {
            return 1;
        } else {
            return 0;
        }
    }
    newArr.sort (compare); // object. Sort() is a built-in JS method that can be called directly
    return newArr;
}
var newArr = bubSort([100, 200, 26, 13, 4, 87, -66, 59]);
console.log(newArr); //[-66, 4, -13, 26, 59, 87, 100, 200]