First, you need to actually call your sort() function:
print(mainArr) # print the unsorted list
print()
sort() # sort the list
print()
print(mainArr) # print the sorted list
This gets you an error:
for x in range(0, mainArr.len - 1):
AttributeError: 'list' object has no attribute 'len'
which is because, indeed, a list does not have a len property. You want to change mainArr.len to len(mainArr).
That then gets you the output:
[5, 2, 3, 6, 1, 4]
[2, 3, 5, 1, 4, 6]
[2, 3, 1, 4, 5, 6]
[2, 1, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
All the output in the middle is emitted by sort() itself as it recurses.
It looks like with that fix, your sort function works, but here are a few simple fixes/suggestions:
sorted is a built-in function, so it's not recommended to use that name for another variable.
- You don't need the
tempVal thing in Python to swap two values; just do a tuple assignment!
- If your function takes the list as an argument, it can sort any list, not just
mainArr.
With those fixes the code looks like:
mainArr = [5, 2, 3, 6, 1, 4]
def sort(arr):
"""Sort the input list 'arr' in-place."""
is_sorted = True
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
is_sorted = False
arr[i], arr[i+1] = arr[i+1], arr[i]
if not is_sorted:
sort(arr)
print(mainArr)
sort(mainArr)
print(mainArr)
I'd also suggest not using recursion (Python doesn't do tail-call optimization by default, so you should avoid using recursion when it's easy to do the same thing with a loop). Using a while loop outside your for loop you'd have something like:
def sort(arr):
"""Sort the input list 'arr' in-place."""
keep_sorting = True
while keep_sorting:
keep_sorting = False
for i in range(len(arr) - 1):
if arr[i] > arr[i+1]:
arr[i], arr[i+1] = arr[i+1], arr[i]
keep_sorting = True
sortedvariable to something different since it's a built-in keyword in Pythonforloop but rather iterate continuously until the iterable is sortedsort()function, which is why it's not doing anything (including raising an error). Once you actually call the function you'll hit the error that @James_481 pointed out.