Home > Blockchain >  what is the error in my sorting algorithm?
what is the error in my sorting algorithm?

Time:11-16

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.

CodePudding user response:

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

CodePudding user response:

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)

  • Related