0

i write this code to sort the element of an array but iam getting this error line 9, in if(a[i]>a[j]): IndexError: list index out of range the same logic for sorting array elements work with java or c correctly. help me to find why this is happening in python . is this due to python syntax or another

from array import *
a=[]
n=int(input("enter number of elements:"))
for i in range(0,n):
    b=input("enter element")
    a.append(b)
for i in range(0,n):
    for j in range(i+1,n):
        if(a[i]>a[j]):
            temp=a[i]
            a[i]=a[j]
            a[j]=temp
print("sorted")
for i in range(0,n-1):
    print(a[i])
    print(a[n-1])
4
  • 1
    use list sort method to sort your list. list.sort() sorts the list. or sorted(list) returns sorted version of list original unaffected. Commented Jun 8, 2017 at 3:27
  • Correct the outer for loop to have the signature: for i in range(0, n - 1) Commented Jun 8, 2017 at 3:28
  • 1
    Please fix up your indenting; whitespace matters in python and the bug may very well be caused by that but there's no way to tell if the code is formatted incorrectly. Commented Jun 8, 2017 at 3:31
  • how can i understand the code where only whitespace matters ,i mean if there is no curly braces to indicate where block of end or started how can i fix the error .sometimes even logic is correct but code doesn't execute Commented Jun 9, 2017 at 18:28

2 Answers 2

1

first you don't need to write list sort method yourself python does it for you. and second no need of third temporary variable to swap value between two variable in python simply a,b=b,a will swap value between a and b

a=[1,5,4,7,8,3,5,4]
for i in range(len(a)):
    for j in range(i+1,len(a)):
        if a[i]>a[j]:
            a[i],a[j]=a[j],a[i]

print(a)

the above code works sorts in ascending order. for descending order change the > to <. it is better to use builtin list sort methods and sorted function to sort any list.

Sign up to request clarification or add additional context in comments.

Comments

0

Here is some improvement to your current code:

a =[]
n = int(input("enter number of elements: "))

for i in range(0, n):
    b=input("enter element: ")
    a.append(b)
# You can also, use:
# for i in range(len(a))
for i in range(0, n):
    # Same:
    # for j in range(i+1, len(a))
    for j in range(i+1, n):
        # Be aware:
        # if the data passed to the list a cannot be converted
        # into an integer, this code will throw a ValueError exception
        if int(a[i]) > int(a[j]):
            # You don't need to create a 'temp' variable
            # Python can handle it dynamically
            a[i], a[j] = a[j], a[i]

            print("Sorted")
            print(" ".join(a))

Demo:

enter number of elements: 4
enter element: 5
enter element: 1
enter element: 4
enter element: 3
Sorted
1 5 4 3
Sorted
1 4 5 3
Sorted
1 3 5 4
Sorted
1 3 4 5

PS: I recommend you using the Python built-in sorted(), or list.sort() which is a in-place list sorting

2 Comments

thanks @Chiheb Nexus i have assignment to sort an user entered array without using inbuilt function thats why i created array of int type..i have doubt that in python array still exists or completely replaced by list. one more help how can i understand a code in python since it does not contain any block and only space matters sometimes it is difficult to find where a particular block of code ends and another block started.
@Infinity, well since python uses identation to seperate code's blocks, you may need to work often with python to know where the block begins and where it ends. Identation let your code be more elegant and easy to use. Personally, i like this concept.

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.