sorting a list in python without the sorted function

Question:

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?

Asked By: rajpython

||

Answers:

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.)

Answered By: Ry-

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

🙂

Answered By: Nilesh

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.

Answered By: Old Panda
a = [5,2,4,1]
for i in range(len(a)):
    for j in range(len(a)-1):
        If a[j]>a[j+1]:
            a[j],a[j+1] = a[j+1],a[j]
Print a
Answered By: Iyappan
s = [3, 6, 4, 5, 2, 1, 7, 8, 11, 12]
for k in range(len(s)):
    for m in range(len(s)-1):
        if s[m]>s[m+1]:
            s[m],s[m+1] = s[m+1],s[m]
print s
Answered By: Iyappsys

if time complexity matters then, this can help you,

nums = [8,3,4,2,7,-9,5,0,1]
tmp = []
def get_index(val:int):
    for i in range(0,len(tmp)):
        if tmp[i] > val:
            return i
        else:
            continue

for one_num in nums:
    print(one_num, tmp)
    if len(tmp) == 0:
        tmp.append(one_num) #[8]
    else: # [3,8]
        if one_num > tmp[-1]:
            tmp.append(one_num)
        else:
            tmp.insert(get_index(one_num, ),one_num)
print(tmp)
Answered By: KLAS R
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.