我想在python中实现一个非常简单的Insertion-Sort算法,我可以根据行/列的第n个元素对数组行/列进行排序
spring
变为
A = [(2,1,2),(1,4,1),(3,2,3)]
按行排序和依赖A [0]
所以我写了一个函数
A = [(1,4,1),(2,1,2),(3,2,3)]
我打电话给
import numpy as np
'''
Algorithm to sort array row/columnwise
A : numpy array, x : axis on which to sort (0:=rows, 1:=colums in 2D)
nth : nth element of array to sort
'''
def insertion_sort(A, x, nth):
if x == 0:
for i in range(1, np.size(A, axis=x)):
buffer = A[i]
j = i-1
while j >= 0 and A[j][nth] > buffer[nth]:
A[j+1] = A[j]
j -= 1
A[j+1] = buffer
return A
但是我得到了一个错误,因为缓冲区随着行的依赖性而改变
A = np.array([(2,1,2),(1,4,1),(3,2,3)])
print(insertion_sort(A,0,0))
影响
buffer = A[i]
在循环结束时。我真的不认为这应该发生吗?我错过了什么? 该功能的输出是
A[j+1] = buffer
这是错误的。
答案 0 :(得分:0)
NumPy数组存储在连续的内存位置。因此,ego_graph()
不能通过复制内存地址来完成(这样做会导致A[j+1] = A[j]
和A[j+1]
具有相同的地址),因此通过复制值来完成赋值。
您可以使用A[j]
buffer
的内存位置