---Study on the Road (a) Python data structures and Algorithms (2)-bubble sort, select sort, insert sort

Source: Internet
Author: User



Monologue:



  First Contact algorithm sequencing, full of curiosity and eager to understand the principles, today we first learned three kinds of sorting methods, namely bubble sort, select sort, insert sort. After learning that math knowledge is really important, the more good algorithm requires more knowledge, more refined. Although the first contact is not easy to accept, but I believe that with continuous active learning and practice can be overcome. The most important thing I am interested in studying! enjoy!













first, bubble sort (English: Bubble Sort):



is a simple sort algorithm. It iterates over the sequence of columns to be sorted, compares two elements at a time, and swaps them if their order is wrong. The work of iterating through the series is repeated until no more swapping is needed, meaning that the sequence is sorted. The algorithm is named because the smaller elements will slowly "float" through the switch to the top of the sequence.



The bubbling sorting algorithm works as follows:


    • Compares the adjacent elements. If the first one is larger than the second (ascending), swap them both.
    • Do the same for each pair of adjacent elements, starting with the last pair from the first pair to the end. When this is done, the final element will be the maximum number.
    • Repeat the above steps for all elements, except for the last one.
    • Repeat the above steps each time for fewer elements, until there are no pairs of numbers to compare.
    • Complexity of Time
      • Optimal time complexity: O (n) (indicates that traversing a discovery does not have any elements that can be exchanged, the sort ends.) )
      • Worst time complexity: O (n2)
      • Stability: Stable





Code:




"" "
Bubble Sort
Time complexity O (n * n)
Optimal ordering: O (n) (traversed once and found no exchangeable elements)
Stability: stable
"" "
import time
import random


def new_num (lis):
    "" "Randomly generated 50 numbers added to the list" ""
    for i in range (50):
        j = random.randint (0,100000)
        lis.append (j)
# Starting time
first_time = time.time ()


def bubble_sort_high (list1):
    """Ascending"""
    for j in range (len (list1) -1,0, -1):
        for i in range (j):
            if list1 [i]> list1 [i + 1]: # difference
                list1 [i], list1 [i + 1] = list1 [i + 1], list1 [i]


def bubble_sort_low (list2):
    """descending sort"""
    for j in range (len (list2) -1,0, -1):
        for i in range (j):
            if list2 [i] <list2 [i + 1]: # difference
                list2 [i], list2 [i + 1] = list2 [i + 1], list2 [i]



# Empty list
lis = []

# Add random function to the list
new_num (lis)

# Sort list
bubble_sort_high (lis)
print (lis)

# End Time
last_time = time.time ()

print ("% s when sharing"% (last_time-first_time))










Second, choose the sort


Select sort (Selection sort) is a simple and intuitive sorting algorithm. It works as follows. First find the smallest (large) element in the unordered sequence, place it at the beginning of the sort sequence, and then continue looking for the smallest (large) element from the remaining unsorted elements, and place it at the end of the sorted sequence. And so on until all elements are sorted.



The main advantages of selecting a sort are related to data movement. If an element is in the correct final position, it will not be moved. Select sort every time a pair of elements is exchanged, at least one of them will be moved to its final position, so the table of n elements is sorted for a total of up to n-1 times. In all of the sorting methods that rely entirely on swapping to move elements, choosing a sort is a very good one.





Complexity of Time
    • Optimal time complexity: O (n2)
    • Worst time complexity: O (n2)
    • Stability: Unstable (consider ascending each time to select the maximum case)





Code





"" "
Select sort
Optimal time complexity: O (n * n)
Unstable
"" "


import random
import time


def selection_sort_high (list):
    """    Ascending   """
    # n is equal to list length
    n = len (list)
    # Need n-1 cycles to select operation
    for j in range (n-1):
        # Pick the smallest index
        min_index = j
        # Compare the current position with the element behind its index Select the smallest data
        for i in range (j + 1, n):
            if list [i] <list [min_index]:
                min_index = i
        # If the selected data is incorrect, exchange it
        if min_index! = j:
            list [j], list [min_index] = list [min_index], list [j]


def selection_sort_low (list):
    """  descending sort  """
    n = len (list)
    for j in range (n-1):
        max_index = j
        for i in range (j + 1, n):
            if list [i]> list [max_index]:
                max_index = i
        list [j], list [max_index] = list [max_index], list [j]


def freestyle (list):
    "" "Another expression" ""
    n = len (list)
    for j in range (n-1,0, -1):
        max_index = j
        for i in range (j):
            if list [i]> list [max_index]:
                max_index = i
        list [j], list [max_index] = list [max_index], list [j]


def new_num (lis):
    "" "Randomly generated 50 numbers added to the list" ""
    for i in range (50):
        j = random.randint (0,10000)
        lis.append (j)

first_time = time.time ()
# Empty list
lis = []

# Add random function to the list
new_num (lis)

# Sort list
selection_sort_high (lis)
print (lis)

# End Time
last_time = time.time ()

print ("% s when sharing"% (last_time-first_time))










Third, insert sort


Insert Sort (English: insertion sort) is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, for unsorted data, to scan from backward forward in the sorted sequence, to find the appropriate position and insert it. Insert sort on implementation, in the process of backward forward scanning, the ordered elements need to be moved back and forth gradually, providing the insertion space for the newest elements








Complexity of Time
    • Optimal time complexity: O (n) (in ascending order, sequence already in ascending state)
    • Worst time complexity: O (n2)
    • Stability: Stable





Code:


"" "
Insert sort
Time complexity: O (n * n)
Stability: stable

"" "
import random
import time


def insert_sort (list):
     n = len (list)
     # Insert from the second position, the index is 1
     for j in range (1, n):
         # Compare starting from the jth element, if less than the previous element, swap positions
         for i in range (j, 0, -1):
             if list [i] <list [i-1]:
                 list [i], list [i-1] = list [i-1], list [i]


def new_num (lis):
     "" "Randomly generated 50 numbers added to the list
     for i in range (50):
         j = random.randint (0,10000)
         lis.append (j)

first_time = time.time ()
# Empty list
lis = []

# Add random function to the list
new_num (lis)

# Sort list
insert_sort (lis)
print (lis)

# End Time
last_time = time.time ()

print ("% s when sharing"% (last_time-first_time)) 





---Study on the Road (a) Python data structures and Algorithms (2)-bubble sort, select sort, insert sort


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.