Insertion sort invariant assertion fails

Posted by user1661211 on Stack Overflow See other posts from Stack Overflow or by user1661211
Published on 2012-09-10T21:01:05Z Indexed on 2012/09/10 21:38 UTC
Read the original article Hit count: 170

Filed under:
|
|
|

In the following code at the end of the for loop I use the assert function in order to test that a[i+1] is greater than or equal to a[i] but I get the following error (after the code below). Also in c++ the assert with the following seems to work just fine but in python (the following code) it does not seem to work...anyone know why?

import random

class Sorting:
    #Precondition: An array a with values.
    #Postcondition: Array a[1...n] is sorted.
    def insertion_sort(self,a):
        #First loop invariant: Array a[1...i] is sorted.
        for j in range(1,len(a)):
            key = a[j]
            i = j-1
            #Second loop invariant: a[i] is the greatest value from a[i...j-1]
            while i >= 0 and a[i] > key:
                a[i+1] = a[i]
                i = i-1
            a[i+1] = key
            assert a[i+1] >= a[i]
        return a

    def random_array(self,size):
        b = []
        for i in range(0,size):
            b.append(random.randint(0,1000))
        return b


sort = Sorting()
print sort.insertion_sort(sort.random_array(10))

The Error:

Traceback (most recent call last):
File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 27, in          <module>
  print sort.insertion_sort(sort.random_array(10))
File "C:\Users\Albaraa\Desktop\CS253\Programming 1\Insertion_Sort.py", line 16, in insertion_sort
    assert a[i+1] >= a[i]
AssertionError

© Stack Overflow or respective owner

Related posts about python

Related posts about sorting