1.sorts method python (2)Bogo Sort

算法思想:

https://blog.csdn.net/qq_38780163/article/details/80805545

 

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
import random
            

def bogo_sort(data):
      data_num = len(data)      
      list_all = []
      if data_num <2:
           return data,list_all   
      for i in range (0,data_num-1):
            if data[i]>data[i+1]:
                  list_all.append(1)
                  break
            else:
                  list_all.append(0)
      if np.sum(list_all) >0:
            random.shuffle(data)
            data = bogo_sort(data)
      #elif np.sum(list_all) ==0:
           # return data,list_all
      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 = [ 19, 25, 26, 29,8,9,11]
                
         data = bogo_sort(data)

缺点:变量冗余

answers:

"""
This is a pure python implementation of the bogosort algorithm
For doctests run following command:
python -m doctest -v bogo_sort.py
or
python3 -m doctest -v bogo_sort.py
For manual testing run:
python bogo_sort.py
"""

from __future__ import print_function
import random


def bogo_sort(collection):
    """Pure implementation of the bogosort algorithm in Python
    :param collection: some mutable ordered collection with heterogeneous
    comparable items inside
    :return: the same collection ordered by ascending
    Examples:
    >>> bogo_sort([0, 5, 3, 2, 2])
    [0, 2, 2, 3, 5]
    >>> bogo_sort([])
    []
    >>> bogo_sort([-2, -5, -45])
    [-45, -5, -2]
    """

    def isSorted(collection):
        if len(collection) < 2:
            return True
        for i in range(len(collection) - 1):
            if collection[i] > collection[i + 1]:
                return False
        return True

    while not isSorted(collection):
        random.shuffle(collection)
    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:\n').strip()
    unsorted = [int(item) for item in user_input.split(',')]
    print(bogo_sort(unsorted))

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

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

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

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

分享到微信朋友圈

×

扫一扫,手机浏览