0
import math

array = [16,5,3,4,11,9,13]


for x in array[0:len(array)-1]:
    key=x
    index=array.index(x)
    posj=index
    for y in array[index+1:len(array)]:
        if y<key:
            key=y
            posj=array.index(y)
    if index!=posj:
        hold=array[index]
        array[index]=key
        array[posj]=hold


print(array)

I'm trying to implement insertion sort. It appears after using the debugger that in every loop iteration, it is using the array [16,5,3,4,11,9,13] instead of the updated array that results after a loop iteration.

How can I make x be the updated element for the given indicie?

4
  • 2
    array[0:len(array)-1] creates a copy of array Commented Aug 27, 2020 at 7:17
  • I see. Then how do I keep this copy updated? Commented Aug 27, 2020 at 7:17
  • 2
    Since you haven't assigned the copy to any variable you can't. I'm also unsure why you are creating a copy at all instead of iterating over the array by index Commented Aug 27, 2020 at 7:20
  • Good point, I guess my ignorance with Python is showing. Should I delete this question? Commented Aug 27, 2020 at 7:22

1 Answer 1

2

Instead of

for x in array[0:len(array)-1]:

try

for x in array:

Output

[3, 4, 5, 9, 11, 13, 16]

Sign up to request clarification or add additional context in comments.

4 Comments

Doing it this way leaves me with only the option of iterating through every element though. How can I iterate through only n-1 elements without making a copy of the array? Not that it matters in this particular implementation, but for future refrence I would like to know.
use a counter and break condition
So what the difference between your solution and array[0:len(array)].
array[0:len(array)] creates a copy

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.