整形数组未排序前的顺序如下:
[42,20,17,13,28,14,23,15]
第一趟排序,我们从后一个元素15开始,不断与之相邻的元素进行比较,如果比15大,则交换位置,如果比15小,就交换比较元素,第一趟之后,我们得到数组里的最小元素13,而且13也位于数组的第一个元素了,通过不断的排序比较,在比较了数组长度-1次以后,该数组的所有元素已经根据大小排好顺序了
冒泡

//第一种
function bubbleSort(arr) {
  var i = arr.length, j;
    var tempExchangVal;
    while (i > 0) {
        for (j = 0; j < i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
                tempExchangVal = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = tempExchangVal;
            }
        }
        i--;
    }
    return arr;
}

bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);


//第二种
function bubbleSort(array) {
  // change code below this line
    array = array.sort(function(a,b){
        return a - b;
})
  // change code above this line
   return array;
}
bubbleSort([1,4,2,8,345,123,43,32,5643,63,123,43,2,55,1,234,92]);
Last modification:May 10th, 2020 at 12:40 pm
如果觉得我的文章对你有用,请随意赞赏