0

I am trying to make a sorting algorithm using python, but I am encountering a problem and I can't figure it out. I'll paste my code below.

basic function:

  • gets an array of numbers
  • goes through and checks if a number is bigger than the next one
  • if it is, swap it and set a variable to tell the function to run again at the end the numbers should be in ascending order
mainArr = [5, 2, 3, 6, 1, 4]
def sort():
  sorted = True
  tempVal = 0
  for x in range(0, mainArr.len - 1):
    if mainArr[x] > mainArr[x+1]:
      sorted = False
      tempVal = mainArr[x]
      mainArr[x] = mainArr[x+1]
      mainArr[x+1] = tempVal
      sorted = False
  print(mainArr)
  if not sorted:
    sort()
print("\n\n")
print(mainArr)

I have checked the code, but I think it needs a fresh set of eyes.

4
  • 1
    Hello and welcome to SO. Please change your sorted variable to something different since it's a built-in keyword in Python Commented Nov 15, 2022 at 17:22
  • Also, is there a particular error? Usually sorting algorithms don't run in one for loop but rather iterate continuously until the iterable is sorted Commented Nov 15, 2022 at 17:23
  • 1
    Please could you paste the specific error you are getting into your question? Commented Nov 15, 2022 at 17:24
  • Your code never calls the sort() 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. Commented Nov 15, 2022 at 17:32

2 Answers 2

1

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 thetempVal 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
Sign up to request clarification or add additional context in comments.

Comments

0

You haven't included the specific error message in your question so it's hard to understand what's wrong, but one thing I noticed was that you have written:

mainArr.len.

This doesn't work in python. Len is a function that takes an array as a parameter. You would have to write this:

len(mainArr)

1 Comment

np, if this is the solution please accept it as the answer so other people coming to this question see that this is the correct answer

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.