我已经用 python 编写了快速排序的代码,但是这段代码抛出了一个错误。
----------
k=0
def partition(arr,low_index,high_index):
key = arr[low_index]
i = low_index + 1;
j = high_index
while True:
while (i<high_index and key>=arr[i]):
i+=1
while (key<arr[j]):
j-=1
if i<j:
arr[i,j] = arr[j,i]
else:
arr[low_index,j]=arr[j,low_index]
return j
def quicksort(arr,low_index,high_index):
if low_index < high_index:
j = partition(low_index,high_index,arr)
print("Pivot element with index "+str(j)+" has thread "+str(k))
if left<j:
k=k+1
quicksort(arr,low_index, j - 1)
if i<right:
k=k+1
quicksort(arr,j+1,high_index)
return arr
n = input("Enter the value n ")
arr=input("Enter the "+str(n)+" no. of elements ")
brr=quicksort(arr,0,n-1)
print("Elements after sorting are "+str(brr))
----------
它抛出的错误是
输入值 n 4
输入 4 号。元素 [5,6,2,7] 追溯(最近调用最后一次):文件“C:\Users\devendrabhat\Documents\dev\dev\quick.py”,第 38 行,在 brr=quicksort(arr,0 ,n-1) TypeError: 不支持的操作数类型 -: ‘str’ 和 ‘int’
原文由 Devendra Bhat 发布,翻译遵循 CC BY-SA 4.0 许可协议
n 是字符串。所以你需要把它改成int:
如果您在第 37 行输入 [5,6,2,7],python 会将其解释为类似“[5,6,2,7]”的字符串。因此,您需要将字符串转换为列表。