Eight sort of bubble sort 20191209-

1. Bubble Sort

The core idea of ​​the algorithm

Array arr [n], starting from the first number, take arr [i] and the following number arr [i + 1] are compared, if the position arr [i] later than the larger of two numbers exchanged so that after traversing the array once, the largest in the last row of the data plane, then continue to discharge the remaining number of cycles n-1, until all the sorting, since every time the maximum pushed to the bottom, it as if bubbling, so called bubble sort, execute particular logic is as follows:

  1. Taking a first number and a second number of n back to compare the size of the number in the n-th position of the maximum value if the position error after a switching position,
  2. Taking a first number and the second number back to compare the size of the n-1, n-1 in the first position if the position error value larger exchanging a second position after the end of, a
  3. Take the first number and the second back to the first magnitude comparing the number ni, ni th position if the position error after the exchange position, a large value of the i
  4. Repeat the steps until the end of Appeals ordering

Code

def bubbleSort(arr):
    for i in range(len(arr)):
        for j in range(len(arr)-i-1):
            if arr[j]>arr[j+1]:
                arr[j],arr[j+1] = arr[j+1],arr[j]
    return arr

Perform parsing

Using two layers for loop, the outer control the number of rounds of comparison, comparing the inner specifically, len (arr) -i-1 is reduced by one for each comparison a number n that is the number of the first round of comparison, a second round of comparison n- number 1, the number n is not involved in the comparison, because the first sorting round has been placed on the maximum number of the n-th position

to sum up

Bubble sort is a relatively readily appreciated by sorting algorithm, the time complexity of the worst case is O (n- 2 )

Guess you like

Origin www.cnblogs.com/hyj691001/p/12013398.html
Recommended