Sorting algorithm (iii) the Python implementation and algorithm optimization of bubbling, selecting sort

Source: Internet
Author: User

Say in front


The last year is too busy, blog long grass. Recently used Python to achieve a common sorting algorithm for everyone's reference.

Java version sorting algorithm and optimization, see the previous article.

Simple ordering of sorting algorithms (bubbling, selecting, inserting)

Sorting algorithm (ii) heap sequencing



1. Sorting Concepts

Please refer to the previous 2 articles for further review.



2. Simple sort of bubble method python implementation and optimization


Schematic diagram

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M02/07/40/wKiom1nF8CTRGF7IAACgLGM-eko688.png "title=" Bubble method schematic diagram 1 "width=" "height=" 283 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:283px; "alt=" Wkiom1nf8ctrgf7iaacglgm-eko688.png "/>

650) this.width=650; "src=" Https://s1.51cto.com/wyfs02/M00/A5/F1/wKioL1nF8Cix7ybrAAByZegzjnI171.png "title=" Bubble method schematic diagram 2 "width=" "height=" 131 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:131px; "alt=" Wkiol1nf8cix7ybraabyzegzjni171.png "/>


2.1. Basic realization


Num_list = [    [1, 9, 8, 5, 6, 7, 4, 3,  2],    [1, 2, 3, 4, 5, 6, 7, 8, 9]]nums  = num_list[1]print (nums) Length = len (nums) count_swap = 0count = 0#  bubble_sortfor i in range (length):     for j in range ( LENGTH-I-1):        count += 1         if nums[j] > nums[j+1]:             tmp = nums[j]             nums[j] = nums[j+1]             nums[j+1] = tmp            count_ Swap += 1print (Nums,&nbsP;count_swap, count) 


2.2, optimize the implementation


Idea: If there is interaction in this round, the order is not correct, if this round is not exchanged, the description is the target order, the direct end of the sort.


Num_list = [    [1, 9, 8, 5, 6, 7, 4, 3,  2],    [1, 2, 3, 4, 5, 6, 7, 8, 9],     [1, 2, 3, 4, 5, 6, 7, 9, 8]]nums = num_ List[2]print (nums) Length = len (nums) count_swap = 0count = 0# bubble_sortfor  i in range (length):     flag = false    for  j in range (length-i-1):         count += 1         if nums[j] > nums[j+1]:             tmp = nums[j]             nums[j] = nums[j+1]              nums[j+1] = tmp            flag =  true # swapped            count_ swap += 1    if not flag:         breakprint (Nums, count_swap, count)



Summary :

The bubbling method requires a round-wheel comparison of data.

optimization, you can set a marker to determine if there is a data exchange occurring on this wheel, and if no interchange occurs, you can end the sort, and if an interchange occurs, proceed to the next round of sorting

Worst-case scenario is that the initial order is exactly the opposite of the target sequence, with the number of traversal 1,..., n-1 N (n-1)/2

The best sort scenario is that the initial order is exactly the same as the target order and the number of traversal n-1

Time complexity O (n^2)



3, simple sorting of the choice of sorting Python implementation and optimization


Select the core of the sort: each round compares to find an extremum (maximum or minimum) on one end, and then find the extremum for the remaining number until the comparison is over.


Schematic diagram

650) this.width=650; "src=" Https://s3.51cto.com/wyfs02/M02/A5/F1/wKioL1nF8Frhx7cIAAC8VirJv_A194.png "title=" Select sort schematic "width=" "height=" 304 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:700px;height:304px; "alt=" Wkiol1nf8frhx7ciaac8virjv_a194.png "/>


3.1. Basic realization


M_list = [    [1, 9, 8, 5, 6, 7, 4, 3, 2 ],    [1, 2, 3, 4, 5, 6, 7, 8, 9],     [9, 8, 7, 6, 5, 4, 3, 2, 1],    [1,  1, 1, 1, 1, 1, 1, 1, 1]]nums = m_list[0]length =  Len (nums) print (nums) count_swap = 0count_iter = 0for i in range (length):     maxindex = i    for j in range (i +  1, length):        count_iter += 1         if nums[maxindex] < nums[j]:             maxindex = j    if i ! = maxindex:        tmp = nums[i]        nums[ I] = nums[maxindex]        nums[maxindex] = tmp         count_swap += 1print (nums, count_swap,  Count_iter)


3.2, optimize the implementation--two Yuan Select sort


Idea: Reduce the number of iterations, one round to determine the number of 2, that is, the maximum number and the decimal.


M_list = [    [1, 9, 8, 5, 6, 7, 4, 3, 2 ],    [1, 2, 3, 4, 5, 6, 7, 8, 9],     [9, 8, 7, 6, 5, 4, 3, 2, 1],    [1,  1, 1, 1, 1, 1, 1, 1, 1]]nums = m_list[3]length =  Len (nums) print (nums) count_swap = 0count_iter = 0#  Two Yuan Select sort For i in range (length // 2):     maxindex = i    minindex =  -i - 1    minorigin = minindex         for j in range (i + 1, length - i):   #   Less than one         count_iter += 1    each time around      if nums[maxindex] < nums[j]:             maxindex = j        if nums[minindex]  > nums[-j - 1]:             minindex = -j - 1         #print (Maxindex,minindex)     if i != maxindex:        tmp  = nums[i]        nums[i] = nums[maxindex]         nums[maxindex] = tmp         count_swap += 1        #  to update the index if the minimum value has been exchanged         if i == minindex or i ==  Length + minindex:            minindex = maxindex         if minorigin != minindex:         tmp = nums[minorigin]        nums[ minorigin] = nums[minindex]        nums[minindex] =  tmp        count_swap += 1print (Nums, count_swap,  count_iter)


3.3. Optimization of equivalence


Ideas: Two yuan when sorting, each round can know the maximum and minimum value, if a round the maximum minimum value is the same, indicating that the remaining numbers are equal, the direct end of the sort.


M_list = [    [1, 9, 8, 5, 6, 7, 4, 3, 2 ],    [1, 2, 3, 4, 5, 6, 7, 8, 9],     [9, 8, 7, 6, 5, 4, 3, 2, 1],    [1,  1, 1, 1, 1, 1, 1, 1, 1]]nums = m_list[3]length =  Len (nums) print (nums) count_swap = 0count_iter = 0#  Two Yuan Select sort For i in range (length // 2):     maxindex = i    minindex =  -i - 1    minorigin = minindex         for j in range (i + 1, length - i):   #   Less than one         count_iter += 1    each time around      if nums[maxindex] < nums[j]:             maxindex = j        if nums[minindex]  > nums[-j - 1]:             minindex = -j - 1     #print (Maxindex,minindex)      if nums[maxindex] == nums[minindex]: #  Elements Same          break    if i != maxindex:         tmp = nums[i]        nums[i] = nums[maxindex ]        nums[maxindex] = tmp         count_swap += 1        #  if the minimum value has been exchanged, To update the index         if i == minindex or i == length +  Minindex:            minindex = maxindex     if minorigin != minindex:         tmp = nums[minorigin]        nums[minorigin] =  nums[minindex]        nums[minindex] = tmp         count_swap += 1print (Nums, count_swap, count_iter)


3.4, the equivalence situation optimization advanced


Ideas:

[1, 1, 1, 1, 1, 1, 1, 1, 2] In this case, the smallest index found is-2, the maximum index 8, the code above will be exchanged 2 times, the minimum two 1 exchange is useless, so, add a judgment.


M_list = [    [1, 9, 8, 5, 6, 7, 4, 3, 2 ],    [1, 2, 3, 4, 5, 6, 7, 8, 9],     [9, 8, 7, 6, 5, 4, 3, 2, 1],    [1,  1, 1, 1, 1, 1, 1, 1, 1],    [1, 1, 1,  1, 1, 1, 1, 1, 2]]nums = m_list[4]length = len (nums) print ( Nums) count_swap = 0count_iter = 0#  Two Yuan Select sort For i in range (length // &NBSP;2):     maxindex = i    minindex = -i -  1    minorigin = minindex         For j in range (i + 1, length - i):  #  less than one   each time around        count_iter += 1        if nums[ maxindex] < nums[j]:             maxindex = j        if nums[minindex] >  nums[-j - 1]:            minindex =  -j - 1    print (Maxindex,minindex)          if nums[maxindex] == nums[minindex]: #  same Element          break            if i  != maxindex:        tmp = nums[i]         nums[i] = nums[maxindex]         nums[maxindex] = tmp        count_swap += 1         #  if the minimum value has been swapped, update the index         if i ==  minindex or i == length + minindex:             minindex = maxindex        The          #  minimum index is different, but the same value does not need to be exchanged     if  minorigin != minindex and nums[minorigin] != nums[minindex]:         tmp = nums[minorigin]         nums[minorigin] = nums[minindex]        nums[minindex]  = tmp        count_swap += 1         prinT (Nums, count_swap, count_iter) 


There may be some special cases that can be optimized, but all of them are optimized for exceptions, and the whole algorithm is limited.



Summarize


Simple select sort requires data round-wheel comparison and finds extrema in each round

There is no way to know whether the current wheel has reached the sorting requirements, but it is possible to know whether the extremum is at the target index position

Traversal count 1,..., n-1 N (n-1)/2

Time complexity O (n^2)

Reduced switching times, improved efficiency, slightly better performance than bubbling method




This article from "The End of Nanshan" blog, declined to reprint!

Sorting algorithm (iii) the Python implementation and algorithm optimization of bubbling, selecting 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.