Python bubble sort

Source: Internet
Author: User

Bubble Sort:

There is a set of numbers to be sorted, and we are here to sort the numbers in small to large order.
Compares the first number (40) to the second number (20), > 20, the swap position. The second number (40) compares to the third number (30), and >30, the swap position. The third number (40) is compared to the fourth number (10), and >10, the swap position. Compares the fourth number (40) to the fifth number (50), <50, and does not move. In this way, the top number is the largest number, and we just need to sort the next four numbers.

#!/usr/bin/env pythonimport randomdef bubble_sort(data):  length = len(data)  for i in range(len(data) - 1):#冒泡n-1次   for j in range(len(data)-i - 1):#比较次数n-i-1    if (data[j] > data[j + 1]):#从小到大        tmp = data[j]        data[j] = data[j + 1]        data[j + 1] = tmpr = random.Random()#定义空列表,并追加数值data = []for n in range(0, 10):  data.append(r.randint(1, 20))print("初始为:")print(data)print("冒泡排序后:")bubble_sort(data)print(data)

Python bubble 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.