2016-07-25 41 views
0

我下面如何從教程實現python3插入排序算法,但我似乎無法理解爲什麼它是「的J - = 1」在此代碼,而不是J + = 1這個插入排序算法中的「j- = 1」是做什麼的?

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)

+2

因爲Ĵ_decreases_的有序數組下降到0,而不是從0 _increases_多達我。 – Gassa

+0

但是,如果我從for循環開始1,不會讓j = 0的下一次迭代? – Vaderstalk

+0

對於'i = 1',是的。對於'i = 2',首先要設置'j = 1'。對於'i = 10',首先要設置'j = 9'。 – Gassa

回答

0

因爲Ĵ從我的價值,並開始下降到0

如果-as你想要做 - 你Ĵ將永遠不會達到0,所以第j你會j增加1!在你的while循環中= 0總是成立,什麼意思是無限循環。插入排序的

0

實施例: enter image description here
正如你可以看到,插入排序從不同於選擇排序的第二元件開始。所以你從繼續增加i開始,從i減少j直到0。因此,在i次置換,你把你發現的第一個地方的最低元素,並從我創建大小i

def insertion_sort(sample): 
    print("initial sample: ",sample) 

    for i in range(1,len(sample)): 
     j = i #start from i and run till 0. 
     while(j!=0 and sample[j] < sample[j-1]): 
      sample[j-1],sample[j] = sample[j],sample[j-1] #swapping if element j-1 > element j to get lowest element on 1st place. 
      j -= 1 #from element i to element 0 
    print("sorted sample: ",sample)