简体   繁体   English

Python列表索引中的递归排序超出范围

[英]Recursive Sorting in Python-list index out of range

I am trying to read a file and sort the data in the array recursively.我正在尝试读取文件并对数组中的数据进行递归排序。 But the data is not sorted after I run the program.但是我运行程序后数据没有排序。 The text file contains many numbers, one number per line.文本文件包含许多数字,每行一个数字。 I want to sort it in ascending order.我想按升序对其进行排序。 For example:例如:

input file:
5
1
2
4
3

Expect output:
1
2
3
4
5

Actual output:
2
1
3
5
4
A=[]
f = open(sys.argv[1], "r")
for row in f:
    A.append(row)
def divide(p, r):
    x = A[r]
    i =p-1
    for j in range(p,r-1):
        if (A[j] <= x):
            i+=1
            temp=A[i] 
            A[i]=A[j]
            A[j]=temp          
    temp2=A[i+1]
    A[i+1]=A[r]
    A[r]=temp2
    return i+1
    
def sort(p, r): 
    if (p < r) :
        q = divide(p,r)
        sort(p, q-1)
        sort(q+1,r)
sort(0,len(A)-1)
for a in A:
    print(a)

I write this program by implementing the pseudocode below, and I am confused about the purpose of the "i" variable.我通过实现下面的伪代码来编写这个程序,我对“i”变量的用途感到困惑。

function sort205(p, r) {
        if (p < r) {
                q = divide(p,r);
                sort205(p, q-1);
                sort205(q+1, r);
        }
}
function divide(p, r) {
        x = A[r];
        i = p-1;

        for j = p to r-1 {
                if (A[j] <= x) {
                        i += 1;
            exchange A[i] with A[j];
                }
        }
    exchange A[i+1] with A[r]
        return (i+1);
}

These lines:这些行:

  • in your pseudo-code for j = p to r-1for j = p to r-1
  • in your python for j in range(p,r-1):在您的 python for j in range(p,r-1):

do not have the same meaning.没有相同的含义。 A python range excludes its second argument. python range不包括其第二个参数。 You probably meant to do for j in range(p,r):您可能打算for j in range(p,r):

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

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