简体   繁体   中英

Reverse Reverse Insertion Sort

given an array A = [5,4,3,2,6]

use insertion sorting algorithm but starting at the last index... sort ascending order (python)

ex: Iteration 1

A=[5,4,3,2,6]

ex: iteration 2

A =[5,4,2,3,6]

and so on until

A= [2,3,4,5,6]

really stuck on this one...


  for j in range(len(arr), j>0):
    value_to_sort = arr[j]
    while arr[j-1] > value_to_sort and j>0:
      arr[j], arr[j-1] = arr[j-1], arr[j]
      i = i+1
  return arr

is what i have so far any help or guidance would be appriciated

Several issues:

  • The second value you pass to range should be an index value, not a condition, and as you want to count down, you need to use the third argument as well. So range(len(arr), -1, -1)

  • The inner loop uses a name that has not been defined: i . It should be defined, and actually used in the array indexing.

  • The value to sort should be compared with values that are at its right (the already sorted partition), so arr[j-1] is not a good value to compare it with.

  • j > 0 in the inner loop condition is not helpful, since the inner loop does not change j

  • Instead of swapping, it is better to only find the right spot to insert the value to sort, and then perform the move after that loop has found it.

Corrected code:

def inssort(arr):
  for j in range(len(arr) - 1, -1, -1):
    value_to_sort = arr[j]
    for i in range(j + 1, len(arr)):
      if arr[i] > value_to_sort:
         break
    else:
      i = len(arr)
    # rotate the value_to_sort in its right position
    arr[j:i-1] = arr[j+1:i]
    arr[i-1] = value_to_sort
  return arr

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