如何在O(n)时间和O(1)空间中对0和1长度n的数组进行排序?我们可以将它推广到0,1,2,......的数组吗?

时间:2015-04-04 20:43:08

标签: sorting

我想对0和1的数组进行排序。我必须在线性时间和恒定空间中对其进行排序。如何在不明确计算0和1 的数量的情况下执行此操作

我做了类似的事情:

sort(array):
    Q0 = Queue()
    Q1 = Queue()
    for i in (0, n-1):
        if array[i] == 0:
            Q0.push(array[i]) 
        if array[i] == 1:
            Q1.push(array[i])
    j = 0
    while Q0:
        array[j] = Q0.pop()
        j += 1
    while Q1:
        array[j] = Q1.pop()
        j += 1

我认为我的解决方案是正确的并且有O(n)时间,但我不确定O(1)空间。有什么帮助吗?

另外,我们可以将排序推广到0,1,2阵列吗?

2 个答案:

答案 0 :(得分:0)

这个想法是通过保留两个指针将所有的交换到数组的末尾并将零交换到数组的开头。 i指向具有1的第一个索引。

这是一个伪代码:

i = 1
for (j = 1 to n)
    if(a[j] == 0)
        swap(a[i], a[j])
        i++

答案 1 :(得分:0)

这是(测试/工作)Python:

# sort array of length n containing values of only 0 or 1
# in time O(n) and space O(1)

a = [1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
        0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0]
first = 0
last  = len(a)-1
print a

# note: don't need temp since values are only 0 and 1
while(last>first):
    if a[first] == 1:
        a[first] = a[last]
        a[last]  = 1
        last    -= 1
    else:
        first   += 1

print a