简体   繁体   中英

Insertion Sort in python using Key

def insertion_sort2(A):
  for i in range(1,len(A)):
      key = A[i]
      j = i-1
      for j in range(i-1,0,-1):
          if A[j] > key :
              A[j+1] = A[j]
          else:
              A[j+1] = key
              break

  for i in range(1, len(arr)):

    key = arr[i]

    j = i-1
    while j >=0 and key < arr[j] :
        arr[j+1] = arr[j]
        j -= 1
    arr[j+1] = key

Hello I have tried both methods to do simple Insertion Sort in c++ it works but in python it is not working,but both of them are giving answers like 1st one:

[56, 77, 77, 77, 77, 77, 77, 99]

2nd one: does not sort even

Note:The second one starts after break and I have not run them both together,I commented out one and then run the other one

First of all you don't go upto the 0th element in the array in the inner loop. In python's range function, the range is counted uptil one before the second term. On putting range(i-1,-1,-1) the range becomes i-1 to 0. Secondly, you are not swapping the two consecutive elements , just assigning (j)th element a value of (j+1)th element. But what about assigning jth value to (j-1)th element. Third, there's no meaning of doing A[j+1] = key as it already is key.

def insertion_sort2(A):
  for i in range(1,len(A)):
      key = A[i]
      j = i-1
      for j in range(i-1,-1,-1):
          if A[j] > key :
              A[j+1], A[j] = A[j], A[j+1]
          else:
              break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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