简体   繁体   English

使用递归对仅包含0和1的列表进行排序

[英]Sorting an list that only contains 0s and 1s using recursion

I need to write a function that sorts a list of only 1s and 0s and I need to use recursion. 我需要编写一个仅对1和0列表进行排序的函数,并且需要使用递归。 I wrote a function that sorts it without recursion(a modified counting sort, with restrictions put in to make it only take in ones and zeros). 我编写了一个无需递归即可对其进行排序的函数(一种经过修改的计数排序,并带有一些限制,使其只能输入1和0)。 Is there any way to rewrite my solution using recursion? 有什么方法可以使用递归重写我的解决方案? Or any solution to this problem that uses recursion(maybe a modified quicksort)? 或使用递归解决此问题的任何解决方案(可能是修改后的quicksort)?

def counting_sort(array):
   """sorting only ones and zeros"""
   count = [0] * 2               

   for a in array:
    count[a] += 1            
   i = 0
   for a in range(2):            
     for x in range(count[a]): 
        array[i] = a
        i += 1
   return array 

This will do it. 这样就可以了。 It may not be the most elegant, but it's simple and easy: 它可能不是最优雅的,但它很简单:

def binSort(array):
    if len(array) == 0:
        return []
    if array[0] == 0:
        return [0] + binSort(array[1:])
    return binSort(array[1:]) + [1]

It looks at the first element in the list, puts zeroes at the beginning and ones at the end, and moves on to the rest of the list. 它查看列表中的第一个元素,在开头放置零,在结尾放置一个,然后移至列表的其余部分。 If you have questions, I'd be happy to answer them. 如果您有任何疑问,我很乐意回答。

This sorts in place in O(n) time: 排序时间为O(n):

def sort(list, fromIndex, toIndex):
    if fromIndex == toIndex:
        return list
    if list[fromIndex] == 0:
        return sort(list, fromIndex + 1, toIndex)
    else:
        list[fromIndex] = list[toIndex]
        list[toIndex] = 1
        return sort(list, fromIndex, toIndex - 1)

unsortedList = [0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 1]
print sort(unsortedList, 0, len(unsortedList) - 1)

The output is: 输出为:

[0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1]

EDIT: Changed the min and max variable names to fromIndex and toIndex. 编辑:将最小和最大变量名称更改为fromIndex和toIndex。

I couldn't resist a temptation to try this with Python iterator fu. 我忍不住要用Python迭代器fu尝试这种诱惑。 The following is recursive, and produces a lazy sequence: 以下是递归的,并产生一个惰性序列:

from itertools import chain

def zero(): yield 0
def one(): yield 1

def sort01(items):
    if not callable(getattr(items, 'next', None)):
        items = iter(items)
    try:
        if items.next() == 0:
            return chain(zero(), sort01(items))
        else:
            return chain(sort01(items), one())
    except StopIteration:
        return tuple()

Here's the demo: 这是演示:

>>> print list(sort01([0, 1, 1, 0, 0, 0, 0, 1]))
>>> [0, 0, 0, 0, 0, 1, 1, 1]

I think you could do it like this, it's linear and sorts inplace. 我认为您可以这样做,它是线性的并且可以就地排序。 Basically it's two pointers, one going from the beginning and shows where 0's end and enother going from the end and showing where 1's starts. 基本上是两个指针,一个从头开始,显示0的结尾,另一个从头开始,显示1的起点。

def mysort(a, i=None, j=None):
    if not i: i = 0
    if not j: j = len(a) - 1
    if i >= j: return
    if a[i] == 1:
        a[j], a[i] = 1, a[j]
        mysort(a, i, j - 1)
    else:
        mysort(a, i + 1, j)

here's the trace: 这是跟踪:

>>> a = [1, 1, 0, 1, 0]
>>> mysort(a)
 i           j
[1, 1, 0, 1, 0]

 i        j 
[0, 1, 0, 1, 1]

    i     j
[0, 1, 0, 1, 1]

    i  j
[0, 1, 0, 1, 1]

       i
[0, 0, 1, 1, 1]

这不是特别快,但是只有一行:

sorted_list = [i for i in original_list if not i] + [i for i in original_list if i]
def sort(arr):
    leftside = []
    rightside = []
    for elem in arr:
        leftside.append(elem) if elem == 0 else rightside.append(elem)

    return leftside + rightside


mylist = [0, 1, 0, 1, 0]

print sort(mylist)

Now, if it wasn't just one and zeros, then your code would begin to look like quicksort with a leftside and a rightside that gets sorted recursively. 现在,如果它不仅仅是一个零,那么您的代码将开始看起来像带有左侧和右侧递归排序的快速排序。 but since it's only 1 and zero, I think it would look like that. 但是因为它只有1和0,所以我认为它看起来像那样。

This is a simple code and easy than any other in this page and this line is line=map(int,input("").split()) takeing the input in a single line and split into a list and mapping all elements to convert into integers 这是一个简单的代码,比此页面中的其他代码都简单,此行是line = map(int,input(“”)。split())),将输入内容放在一行中,并分成一个列表,并将所有元素映射到转换成整数

list=sorted(line) this ia sorting the list of integer elements list = sorted(line)这是对整数元素列表进行排序

n=input() #size of an array
line=map(int,input("").split()) #elements of the list
list=sorted(line) #sorting the list
print (*list) #To print elements with space use *list eg:- 0 0 1 1 1 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM