Python and Bubble sort

Source: Internet
Author: User

Previous article, introduced a very fast sorting algorithm-bucket sequencing, but its disadvantage is too much resources, this time to implement the algorithm will not use too much resources, it is bubble sort.

Questions raised:

Sort the following data in ascending order: 9, 2, 8, 6, 4

Bubble Sort principle:

The bubbling sort is the traversal of the data, which is compared to the next number at a time, if the two numbers are not in the correct order.

As for the above problem, the larger the number, the higher the numbers are, because they are arranged in ascending order. When the two number is compared, if the latter number is smaller than the current number, then the order is incorrect, and the two numbers are exchanged. The process of traversal is as follows:

For the first time, compare the first and second numbers, 9 vs. 2, 9:2 Large, the wrong order, then swap position.

The second and third numbers are compared, because 9 is the second, then 9 is compared with 8, 9 is large, the order is not correct, then the position is swapped.

And so on, the last 9 is like a bubble up to the last one, we call this a trip, there are several comparisons in this trip.

Since a trip is only classified as one number, if there are n digits, a n-1 trip is required.

Because the number after the return does not have to compare again, so each trip only need to compare n-1-i times (I is the number of executed trips).

The key step that can be derived from the bubbling sort is two loops:

1  for(i =0; I < n1; i++){2    for(j =0; J < N-1-I.; J + +)3     if(A[j] > a[j+1]){4temp =A[j];5A[J] = a[j+1];6a[j+1] =temp;7     }8}

Python implementations:

According to the above ideas, the implementation of Python is also the key place to achieve:

1 # Assuming that the variables are all well defined 2  for  in range (len-1):3for in    Range (len-1-i):4      if a[j] > a[j+1]:5       a[j], a[j+1] = a[j+1], a[j]

Here's The complete code: (You can download https://github.com/DIGCreat/pythonAndAlgorithms.git on GitHub)

1 #!/usr/bin/env python2 #-*-Coding:utf8-*-3 " "4 Introduction: This program is mainly used to achieve bubble sorting python, the function of the program is to achieve5 descending order. 6 7 Author: King Date: 2016/08/01 version 18 " "9 Ten classBubblesort (object): One     " " A Self.datas: List of data to sort - Self.datas_len: The length of the data rush - _sort (): Sort function the Show (): Output result function -  - Usage: - Bubblesort (datas) instantiates a Sort object + Bubblesort (datas). _sort () Start sorting, due to sort direct operation - Self.datas, so the sorting results are also + Save in Self.datas A Bubblesort (datas). Show () output results at     " " -     def __init__(self, datas): -Self.datas =datas -Self.datas_len =Len (datas) -  -     def_sort (self): in         #bubble Sort to sort n number, because each traversal is only one number in a row, -         #it is necessary to traverse n-1, so the outermost loop is to loop n-1 times, and to         #To compare the number of each return in each traversal, compare the n-1 +         #The second loop to traverse is n-1-i times, minus the well - -          forIinchRange (self.datas_len-1): the              forJinchRange (self.datas_len-1-i): *                 if(Self.datas[j] < Self.datas[j + 1]): $SELF.DATAS[J], self.datas[j+1] = Panax NotoginsengSelf.datas[j+1], Self.datas[j] -  the     defShow (self): +         Print 'Result is:', A          forIinchSelf.datas: the             PrintI, +         Print "' -  $ if __name__=='__main__': $     Try: -Datas = Raw_input ('Please input some number:') -Datas =Datas.split () thedatas = [Int (datas[i]) forIinchRange (len (datas))] -     exceptException:Wuyi         Pass the  -BLS =Bubblesort (datas) Wu Bls._sort () -Bls.show ()

Summarize:

Bubble sort because it is in the original array directly operation, so it occupies less space resources, in the case of small amount of data is very good. However, since the algorithm involves a double loop, the time of the program to run is quite long in the case of large data volumes, because the data is traversed once and for all.

Finally interested students can pay attention to my public number, can always be timely and convenient to read my article. *^_^*

Scan code follow or search number: King_diary

Python and Bubble sort

Related Article

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.