JS a thorough understanding of this bubble sort

One ❀ lead

In the interview process, the algorithm always escape in the first place, for me, this non-class families born and university people do not touch it mathematical, logical thinking is really more a lack of respect, last night chat with Baidu students into the early hours, feel a big gap, suffered no small blow, so determined and scratched algorithm, doing training-related questions, I may not have the talent, but do a little better than doing nothing stronger, this article from the sort of top ten Speaking bubble sort.

II ❀ bubble sort basic concepts

In the water, the air density is lighter than water, so the water bubbles will continue to go up, this is our life understood bubbling. The bubble sort of concept as well.

For an array, we will compare two adjacent elements, if the former is larger than the latter, you need to swap positions between the two, that is, after a large sink, a small float forward, watch the most simple example .

let arr = [2, 1];
//比较索引0,与索引1的两个元素,如果前者比后者大,交换两者位置。
if (arr[0] > arr[1]) {
    //交换位置
    arr[0] = [arr[1], arr[1] = arr[0]][0]
};
arr; //[1,2]

Of course, this example is particularly simple, because it contains only two elements, so we need only to traverse once, and once only compare to get the final ranking results.

We will upgrade the array, plus one:

let arr = [3,2,1];

At this point only once it is clear that the comparison can not solve the problem, but a small number, we try to split the comparison process.

  • The first time through
    • First comparison
      • 3 is larger than 2, the exchange position, the array element [2,3,1];
    • The second comparison
      • 3 is larger than 1, the exchange position again, to give an array [2,1,3];

The first time through the end of this time, we found that the current array and no sequencing is complete, still need to traverse once:

  • Second pass
    • First comparison
      • 2 greater than 1, the exchange position, the array element [1,2,3];

At this sort is complete, why need only compare the second time again? This is because the first time through the array will certainly be the largest item to the current end of the array , the second comparison does not make sense.

To demonstrate this, we will upgrade the array again, and then to add one, split as follows:

let arr = [4,2,3,1];
  • The first time through
    • First comparison
      • 4 greater than 2, the exchange position, the array element [2,4,3,1];
    • The second comparison
      • 4 greater than 3, the exchange position, the array element [2,3,4,1];
    • Third comparison
      • 4 greater than 1, the exchange position, producing the array [2,3,1,4], then the end of the first pass, it seems also need to traverse again.
  • Second pass
    • First comparison
      • 2 to 3 hours, without exchanging position, the array remains unchanged [2,3,1,4];
    • The second comparison
      • 3 is larger than 1, the exchange position, the array element [2,1,3,4];

You see, we do not need a third comparison, because the first pass has the largest 4 is moved to the end of the array, so the third comparison meaningless. Since the array not sorted, we need third pass:

  • Third pass
    • First comparison
      • 2 greater than 1, the exchange position, the array [1,2,3,4];

At this point we've got the final ranking, there is no need for a second and third time Comparison.

Observant students may have found a rule, for the same array, once, every move will traverse the current maximum of elements to the end of the array, and the number of comparisons required to traverse the next few compared to the previous one.

Besides the straightforward point, or the above example, the first traversal need to compare three times, determines the current maximum number of 4. The second pass need only compare two times to determine the current maximum number 3, the third pass need only compare one time, to determine the current maximum number of 2.

We appeal integrated three examples caveat:

  • When the array has two, need to traverse once, compare once.
  • When the array has three, it needs to traverse two times, the first comparator 2, a second comparison times.
  • When the array has four, we need to be traversed 3 times, 3 times first comparator, a second comparator 2, a third comparison times.

We seem to get a conclusion, when there is an array of N items, you need to traverse the N-1 times, and the number of comparisons for each iteration N - the number of the current iteration .

Therefore, we can use for loop 2, the outer layer is used to define the number of traverse, the inner layer is used to define the number of comparisons.

Triple ❀ bubble sort to achieve

Know this rule, we directly on the code:

let arr = [3, 1, 5, 4, 7, 6, 0, 2];

function bubbleSort(arr) {
    var length = arr.length,
        i = 0;
    // 遍历次数为length-1次
    for (; i < length - 1; i++) {
        // 当前遍历的比较次数为length - 当前遍历次数
        for (var j = 0; j < length - i; j++) {
            if (arr[j] > arr[j + 1]) {
                arr[j] = [arr[j + 1], arr[j + 1] = arr[j]][0];
            };
        };
    };
    return arr;
};

bubbleSort(arr); //[0, 1, 2, 3, 4, 5, 6, 7]

Baidu Encyclopedia to the outer code example uses the while loop, the same idea, as follows:

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;
};
 
var arr = [3, 2, 4, 9, 1, 5, 7, 6, 8];

But this code there is a problem, we know that when in front of an array of N items, you need to traverse the N-1 times, it is clear that the use of this code while(i>0)would be meaningless more than once, this changed while(i>1)a bit better.

What about the bubble sort array stop here, I am clumsy, in order to explain the bubbling process, only to find the law to take to deepen understanding, if there is inappropriate described herein, also pointed out that hope, then by the end of this article.

Reference wantonly ❀

Sort - Bubble Sort
three minutes thorough understanding of the bubble sort

Guess you like

Origin www.cnblogs.com/echolun/p/12638903.html