0

I need to sort this list without using built-in sort(). I figured I could use insertion sort, but I've never really used it before. My code doesn't seem to be working. What is wrong with it? Thank you.

fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']



for i in range(1, len(fruits)):
    tmp = fruits[i]
    j = i-1;
    while (j>0 and fruits[j] > tmp):
        fruits[j+1] = fruits[j]
        j = j-1
        fruits[j+1] = tmp
print(fruits)
6
  • 1
    Are you actually calling insertion_sort anywhere? If you did, you'd get a NameError, as lens isn't defined. Commented Oct 8, 2017 at 11:35
  • Also - if you're just beginning - don't get into the habit of ending lines with ; - they're not required... Commented Oct 8, 2017 at 11:36
  • I followed your suggestions. thanks! still trying to figure out what's wrong Commented Oct 8, 2017 at 11:41
  • So what is the output of fruits you're getting...? Commented Oct 8, 2017 at 11:42
  • I still get the original 'fruits' list. ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry'] Commented Oct 8, 2017 at 11:43

5 Answers 5

1

This works perfectly too!

Fruits= ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
def insertionSortFruits():
    for i in range(1,len(Fruits)):
        key=Fruits[i]
        j=i-1
        while j>=0 and key<Fruits[j]:
            Fruits[j+1]=Fruits[j]
            j=j-1
        Fruits[j+1]=key
    print(Fruits)

#Testing
insertionSortFruits()
Sign up to request clarification or add additional context in comments.

Comments

0

The swap operation which appears in the inner loop seems quite strange. If I were a betting person I'd say that's where the error occurs.

Try doing a clean "swap", like you'd do it for three variables:

a = 10
b = 20
tmp = a
a = b
b = tmp
print(a) # prints 20
print(b) # prints 10

Your code will become something like:

for i in range(1, len(fruits)):
    j = i-1
    while j >= 0 and fruits[j] > fruits[j+1]:
        # Swap the two consecutive elements which are unsorted
        tmp = fruits[j]
        fruits[j] = fruits[j+1]
        fruits[j+1] = tmp
        # Prepare to process previous two consecutive elements
        j = j-1

1 Comment

It makes sense! Thanks for your help!
0

First replace lens() by len().

In other hand, you not apply your function over fruits array, you only declare function.

Finally, arrays start at index 0, so j must be> = 0.

Corrected code:

fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']

def insertion_sort(fruits):

   for i in range(1, len(fruits)):
       tmp = fruits[i]
       j = i-1;
       while (j>=0 and fruits[j] > tmp):
           fruits[j+1] = fruits[j];
           j = j-1;
      fruits[j+1] = tmp;
   return fruits

if __name__ == "__main__":

     fruits2 = insertion_sort(fruits)
     print(fruits2)

2 Comments

Thank you! I understand the first part, but what does if name p == "main" part do??
if name == "main" is for execute a .py how "main program"
0

I changed two things and it works. Not exactly meant as an answer but might help you forward.

fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']

for i in range(0, len(fruits)):
    tmp = fruits[i]
    j = i-1;
    print(fruits)
    while (j>-1 and fruits[j] > tmp):
        fruits[j+1] = fruits[j] 
        j = j-1
        fruits[j+1] = tmp

print(fruits)

Could be made smaller this way:

fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']

for i in range(len(fruits)):

    tmp = fruits[i]
    j = i-1 # stop index
    while (j > -1 and fruits[j] > tmp):
        fruits[j:j+2] = tmp,fruits[j] #swap places
        j -= 1

print(fruits)

Returns:

['apple', 'banana', 'cherry', 'grape', 'peach', 'strawberry']

1 Comment

That makes sense! Thank you for your help
0
fruits = ['grape', 'banana', 'strawberry', 'apple', 'peach', 'cherry']
for i in range(1,len(fruits))
temp=fruits[i]
k = i
    while k > 0 and tmp < fruits[k - 1]:
        fruits[k] = fruits[k - 1]
        k -= 1
    fruits[k] = tmp
print fruits

your loop will execute one time less as j=i-1 j>0 it should be j>-1

1 Comment

I understand now. Thank you for your help!

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.