sifeddine1337
sifeddine1337

Reputation: 3

sort a list-tuples from smallest to largest (using only loops and conditions without built-in sort )

I arranged a list of numbers from smallest to largest In the following way :

my_list = [-5,3,0,9,-8,1]
for i in range(len(my_list)):
  for x in range(len(my_list)-1):
    if my_list[x] > my_list[x+1]:
      my_list[x], my_list[x+1] = my_list[x+1], my_list[x] 
print(my_list)

output is : [-8, -5, 0, 1, 3, 9]

Now I have a list of tuples :

list_tuple = [(1, 5), (1, 2), (1, 4), (1, 3), (1, 1)]

I want to arrange them the same way from smallest to largest by element [1] To be like this :

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)]

Without using built-in sort

Upvotes: 0

Views: 195

Answers (1)

yw12345
yw12345

Reputation: 36

list_tuple = [(1, 5), (1, 2), (1, 4), (1, 3), (1, 1)]

n = len(list_tuple)

for i in range (0, n):
    for x in range (0, n-i-1):
        if list_tuple[x][1] > list_tuple[x+1][1]:
            y = list_tuple[x]
            list_tuple[x] = list_tuple[x+1]
            list_tuple[x+1] = y

print (list_tuple)

Output:

[(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)]

Upvotes: 2

Related Questions