python bubble sort, quick row

A bubble sort

1.1, bubbling principle

    1. Compare adjacent elements. If the first is greater than the second, the two of them exchanged.
    2. Do the same work for each pair of adjacent elements, from the beginning of the first pair to the end of the last pair. At this point, it should be the last element is the largest number.
    3. Repeat these steps for all elements, except the last one.
    4. Continued to repeat the above steps for each time fewer and fewer elements, a pair of numbers until there is no need to compare.   

2.1, bubble sort code implementation

def bubble_sort(seq):
    count=len(seq)
    for i in range(0,count):
        for j in range(i+1,count):
            if seq[i]>seq[j]:
                seq[i],seq[j]=seq[j],seq[i]
    return seq
seq=[4,5,2,1,6,3]
print(bubble_sort(seq))

3.1, the time complexity of bubble sort

  1, the best case: if the initial state is the positive sequence file, one pass to complete sort, bubble sort which is the optimal case time complexity of o (n)

  2, the worst case: if the original file is in reverse order, the bubble sort requires two cycles, which is the worst case time complexity o (n ^ 2)

  3, the average time complexity o (n ^ 2)

Second, the fast row

  2.1 fast row principle

   Quick drain is improved bubble sort, extracts a first value as a comparison value to be sorted by the sorting trip data is divided into two separate portions, wherein a portion of all of the data is smaller than the comparison value, the comparison value is larger than the other part, then this way the two parts of the data are quickly sort, the entire sorting process can be recursively performed, and finally to separate the two parts were combined comparison value added together to complete the order.

  Quick drain code implements 2.2 

DEF quck_sort (SEQ):
     IF SEQ == []:
         return []
     the else : 
        Pivot = SEQ [0] 
        low_list = quck_sort ([X for X in SEQ IF X <Pivot]) # than the comparative value is smaller partial recursive sort 
        upper_list = quck_sort ([X for X in SEQ IF X> Pivot]) # is larger than the comparison value of partial recursive ordering 
        return low_list + [Pivot] + upper_list # the three are combined, note converting a comparison value to a list 
Print (quck_sort (SEQ ))

  2.3 fast discharge time complexity

  1, the optimal situation: comparison value list aliquots just two parts, the time complexity of o (nlogn)

  2, the worst case: comparison each recursion values ​​are minimum, leading to a separate list is not balanced, time complexity o (n ^ 2)

  3, the draw time complexity o (nlogn)

Guess you like

Origin www.cnblogs.com/dushangguzhousuoli/p/11028916.html