sorting a list in python without the sorted function

23,865

Solution 1

t = a[j]

followed by

a[j] = t

doesn’t seem right. If you meant to swap them, the second one should be:

a[j + 1] = t

But in Python, that’s better written as:

a[j], a[j + 1] = a[j + 1], a[j]

(Of course, in Python, it’s much better written as quicksort.)

Solution 2

Try This -:

for i in range(len(a)):
    for j in range(len(a) - 1):
        if a[j] > a[j+1]:
            a[j+1], a[j] = a[j], a[j+1]

print a

:)

Solution 3

The last line in your for loop should be a[j+1] = t. I think it's just a code mistake. Take care the next time. Also, in Python, when you want to exchange two variables, you should follow what @minitech and @Nilesh G said.

Share:
23,865
rajpython
Author by

rajpython

Updated on May 09, 2020

Comments

  • rajpython
    rajpython almost 4 years
    import sys
    import pdb
    
    a = [5, 2, 4, 1]
    
    for i in range(len(a)):
        for j in range(len(a) - 1):
            if a[j] > a[j+1]:
                t = a[j]
                a[j] = a[j+1] 
                a[j] = t
    
    print a                   
    sys.exit()
    

    I just tried a C program in Python – a normal sort without the sorted function. Why am I not getting the sorted list?

    • johnsyweb
      johnsyweb over 10 years
      Why "without the sorted() function"?
    • rdodev
      rdodev over 10 years
      @Johnsyweb I'm guessing it's an assignment. Instructors usually request no built-ins so that students how to do it w/o them.
    • rajpython
      rajpython over 10 years
      @rdodev: yes , as you said. in question sessions and interviews , they expect it without inbuilt function.
  • rdodev
    rdodev over 10 years
    In spite of that this is likely a homework assignment, this is spot-on. Hopefully OP will appreciate and learn from it.
  • rdodev
    rdodev over 10 years
    @minitech had already answer the same thing below, just saying.
  • Elizabeth Susan Joseph
    Elizabeth Susan Joseph about 9 years
    I am new to python programming. could you explain why are you using two for loops here?
  • Elizabeth Susan Joseph
    Elizabeth Susan Joseph about 9 years
    I am new to python programming. could you explain why two for loops are used here? . I know this is a silly question. but I am not able to get the concept.
  • Ry-
    Ry- about 9 years
    @ElizabethSusanJoseph: Don’t worry; it doesn’t really make sense. The inner loop is a bubble sort, and the outer loop runs the bubble sort the absolute maximum number of times it’d take to sort the list using bubble sort (actually, once more than that). You’d usually stop when the list was sorted instead.
  • Elizabeth Susan Joseph
    Elizabeth Susan Joseph about 9 years
    @minitech ok first I will understand what is bubble sort ;). I should have told you that I am new to programming as well. I have completed code academies python exercise. I will learn this concept first.