Ich bin nach wie ein Einführungssortieralgorithmus in python3 aus einem Tutorial zu implementieren, aber ich kann nicht scheinen zu verstehen, warum es ist, „j - = 1“ in diesem Code und nicht j + = 1.Was macht die "j- = 1" in diesem Einfügesortieralgorithmus?
sample1 = [5,3,2,4,6]
def insertion_sort(sample):
print("initial sample: ",sample)
for i in range(1,len(sample)):
j = i
while(j!=0 and sample[j] < sample[j-1]):
sample[j-1],sample[j] = sample[j],sample[j-1]
j -= 1 #why this and not j += 1 instead?
print("sorted sample: ",sample)
insertion_sort (sample1)
Da j _decreases_ von i auf 0, nicht von 0 bis i _increases_ zu schaffen. – Gassa
Aber wenn ich bei 1 aus der for-Schleife beginnt, macht es nicht die nächste Iteration von j = 0? – Vaderstalk
Für "i = 1", ja. Für "i = 2" ist die erste Sache, "j = 1" zu setzen. Für "i = 10" ist die erste Sache, "j = 9" zu setzen. – Gassa