1.sorts method python (3)bubble_sort

原理:

http://bubkoo.com/2014/01/12/sort-algorithm/bubble-sort/

my stupid code:

# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 10:14:28 2019

@author: yue zhang

E-mails: yuezh2015@163.com
"""
import numpy as np
            

def bubble_sort(data):
      data_num = len(data)      

      if data_num <2:
           return data 
      for j in range (data_num-1,0,-1):
            for i in range (0,j):  
                    if data[i]>data[i+1]:
                          data[i],data[i+1] = data[i+1],data[i]

      return data

                 
if __name__ == '__main__':
         data = [10,20,50,3,5,7,9,11,88,55,77,56,1,2,4,555,19, 25, 26, 29 ,38 ,50 ,80, 91 ,86, 78 ,66 ,46, 32 ,19 ,15 , 7]
         #data = [ 59, 25,50,3]         
        
         data= bubble_sort(data)

缺点:不论什么data,运行次数一定,效率不高。

 

answer

    
from __future__ import print_function


def bubble_sort(collection):
    """Pure implementation of bubble sort algorithm in Python
    :param collection: some mutable ordered collection with heterogeneous
    comparable items inside
    :return: the same collection ordered by ascending
    Examples:
    >>> bubble_sort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]
    >>> bubble_sort([])
    []
    >>> bubble_sort([-2, -5, -45])
    [-45, -5, -2]
    
    >>> bubble_sort([-23,0,6,-4,34])
    [-23, -4, 0, 6, 34]
    """
    length = len(collection)
    for i in range(length-1):
        swapped = False
        for j in range(length-1-i):
            if collection[j] > collection[j+1]:
                swapped = True
                collection[j], collection[j+1] = collection[j+1], collection[j]
        if not swapped: break  # Stop iteration if the collection is sorted.
    return collection


if __name__ == '__main__':
    try:
        raw_input          # Python 2
    except NameError:
        raw_input = input  # Python 3
    user_input = raw_input('Enter numbers separated by a comma:').strip()
    unsorted = [int(item) for item in user_input.split(',')]
    print(*bubble_sort(unsorted), sep=',')

https://github.com/TheAlgorithms/Python/blob/master/sorts/bubble_sort.py

发布了84 篇原创文章 · 获赞 124 · 访问量 15万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览