Reputation: 111
I have a working simple insertion sort algorithm written in Python. What I'm trying to do is take the output and put it in a new list without altering the original input list. I've been stuck on trying to figure out how to do this and maybe I'm just overthinking it, but I thought I would see if anyone could help. Thanks!
#!/usr/local/bin/python
import sys
import random
def RandomArray(n, max):
A = []
i = 1
while i <= n:
v = random.randint(1, max+1)
if v not in A:
A.append(v)
i = i + 1
return A
A = RandomArray(10,100)
print(A)
def InsertionSort(A):
element = 1
for element in range(0, (len(A))):
w = A[element]
j = element - 1
while (j >= 0) & (A[j] > w):
A[j+1] = A[j]
j = j - 1
A[j+1] = w
return A
print(InsertionSort(A))
Upvotes: 0
Views: 304
Reputation: 16763
You are mutating the list in your sorting function, a simple solution with existing solution would be deepcopy the list, before mutating it.
import copy
def InsertionSort(A):
A = copy.deepcopy(A) # or A = A[:] might work as well in this case
...
return A
As an extra advice, the naming conventions you are using are not pythonic. Function names should be snake cased instead of Pascal cased (I have kept the same just for consistency).
Upvotes: 1