I am new to Python. I wrote a code for quick sort to sort integer numbers in ascending order. Using - Ubuntu 16.10 and python3.5
Code -
import random
a=[]
n=int(input("Enter size :\n"))
for i in range(0,n):
a.append(int(random.randrange(0,100)))
print("Before Sorting:",a)
def quick(a,low,high):
if(low<high):
i=low
j=high
key=a[low]
flag=1
while (flag==1):
i += 1
while(a[i]<key):
i += 1
while (a[j]>key):
j -= 1
if (i<j):
a[i],a[j]=a[j],a[i]
else:
flag=0
a[low],a[j]=a[j],a[low]
quick(a,low,j-1)
quick(a,j+1,high)
# Calling function quick where a = List, 0 = Start Index ,n-1 = Last Index
quick(a,0,n-1)
print("After Sorting:",a)
When i run the code it throws IndexError: list index out of range but if i run the same code with same input it gives correct output. For example - Running the code for 1st time with n = 5
linux@linux-Lenovo-G50-30:~/PYTHON/practice/run1$ python3 quick.py
Enter size :
5
Before Sorting : [55, 23, 57, 86, 20]
Traceback (most recent call last):
File "quick.py", line 30, in <module>
quick(a,0,n-1)
File "quick.py", line 27, in quick
quick(a,j+1,high)
File "quick.py", line 17, in quick
while(a[i]<key):
IndexError: list index out of range
Running the code for 2nd time with n = 5
Enter size :
5
Before Sorting : [6, 5, 93, 84, 32]
Traceback (most recent call last):
File "quick.py", line 30, in <module>
quick(a,0,n-1)
File "quick.py", line 27, in quick
quick(a,j+1,high)
File "quick.py", line 17, in quick
while(a[i]<key):
IndexError: list index out of range
Running the code for 3rd time with n = 5
linux@linux-Lenovo-G50-30:~/PYTHON/practice/run1$ python3 quick.py
Enter size :
5
Before Sorting : [87, 18, 94, 1, 64]
After Sorting : [1, 18, 64, 87, 94]
I am not able to figure out why this happens. I am using Ubuntu 16.10 and python3.5