Bubble sort of thinking python bubble sort

Source: Internet
Author: User

The time complexity of bubble sorting is the idea of O (n^2) bubble sort: compare two adjacent elements each time, and swap them if they're in the wrong order.

For example, there are five numbers: 12, 35, 99, 18, 76, from the big to the small sort, compare the adjacent two bits

    • First trip:
    • First time comparisons: 35, 12, 99, 18, 76
    • Second comparisons: 35, 99, 12, 18, 76
    • Third comparisons: 35, 99, 18, 12, 76
    • Fourth time comparisons: 35, 99, 18, 76, 12

After the first comparison, the smallest of the five numbers is already on the last side, then only the first four numbers are compared, and so on.

    • Second trip
      99, 35, 76, 18, 12
    • Third Trip
      99, 76, 35, 18, 12
    • Four trips
      99, 76, 35, 18, 12
      Compare complete
Bubble sorting principle: Each trip can only be a number of digits, if there are N number to sort, just the number of n-1, that is, to do n-1 operation (the number has been returned without comparison)
#!/usr/bin/env python#Coding:utf-8defBubblesort (nums): forIinchRange (len (nums)-1):#This loop is responsible for setting the number of times the bubble sort is performed         forJinchRange (len (nums)-i-1):#J for List subscript            ifNUMS[J] > Nums[j+1]: nums[j], nums[j+1] = nums[j+1], Nums[j]returnnumsnums= [5,2,45,6,8,2,1]PrintBubblesort (Nums)
Cons: Bubble sorting solves the problem of wasted space in bucket sequencing, but the efficiency of bubble sorting is particularly low

From: http://www.cnblogs.com/qlshine/p/6017957.html

Bubble sort of thinking python 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.