算法未按预期对数组排序

iswrvxsc  于 2021-08-25  发布在  Java
关注(0)|答案(3)|浏览(275)

我用[3,7,5,2,1,4,8]输入得到了以下算法。据说这是快速排序的一部分,它构造了一个分区位置。。输出应该是[3,1,2,5,7,4,8]

我使用了以下python代码:

def partition(x, s, d):
    v = x[s]
    i = s-1
    j = d+1
    while i < j:
        while True:
            i = i+1 
            if x[i] >=v:
                break
        while True:
            j = j-1 
            if x[j] <=v:
                break 
        if (i<j):
            x[i], x[j] = x[j], x[i]

    print (x)
    return j

x = [3, 7, 5, 2, 1, 4, 8]
partition(x, 1, 6)

我无法得到[3,1,2,5,7,4,8],这据说是正确的结果。请帮忙,我尝试了s和d的不同值,它们很可能代表左和右。

l2osamch

l2osamch1#

这是快速排序的分区算法。
因为我们使用 while 循环而不是 do.. while (这就是您的算法中提到的内容 REPEAT... UNTIL ),我们不需要减量 s 和增量 d .

def partition(x, s, d):
    v = x[s]
    i = s
    j = d

    while i < j:
        while x[i] <= v:
            i += 1

        while x[j] >= v:
            j -= 1

        if (i<j):
            x[i], x[j] = x[j], x[i]

    print(x)
    return j

x = [3, 7, 5, 2, 1, 4, 8]
partition(x, 0, 6)
Output:

[3, 1, 2, 5, 7, 4, 8]
bsxbgnwa

bsxbgnwa2#

什么时候 ij 如果已定义,则它们等于开始索引减1,结束索引加1。如果使用这些索引,它们将超出范围,因此将出现错误。因此,当代码到达 REPEAT ... UNTIL 节,则会立即撤消负1和正1。为了避免此问题,我使用了以下代码:

lis = [3,7,5,2,1,4,8]

def partition(x,s,d):
    v = x[s]
    i = s
    j = d
    while i < j:
        while x[i] <= v:
            i += 1
        while x[j] >= v:
            j -= 1
        if i < j:
            x[i], x[j] = x[j], x[i]
    return j

position = partition(lis, 0, 6)
print(position)
print(lis)

输出:

2
[3, 1, 2, 5, 7, 4, 8]

我相信这个位置可以用来划分列表并对其进行进一步排序,但由于缺乏信息,我不确定如何最好地做到这一点。
多亏了另一个答案,我相信混乱是由 REPEAT ... UNTIL 条件语句。通过我的陈述 <= 而不仅仅是 < 我已经获得了期望的输出。

ne5o7dgx

ne5o7dgx3#

def partition(x, s, d):
    v = x[s]
    i = s-1
    j = d+1
    while i < j:
        while True:
            i = i+1 
            if x[i] >v: #--->
                break
        while True:
            j = j-1 
            if x[j] <v: #--->
                break
        if (i<j):
            x[i], x[j] = x[j], x[i]

    print (x)
    return j

x = [3, 7, 5, 2, 1, 4, 8]
partition(x, 0, len(x)-1) #---->
[3, 1, 2, 5, 7, 4, 8]

相关问题