Sort a list in Python without sort Function
Last Updated :
24 Aug, 2023
Python Lists are a type of data structure that is mutable in nature. This means that we can modify the elements in the list. We can sort a list in Python using the inbuilt list sort() function. But in this article, we will learn how we can sort a list in a particular order without using the list sort() method.
Sort a List Without Using Sort Function in Python
Sorting is nothing but arranging the elements of a list in a particular order and this order can be either increasing or decreasing in nature. We can sort a list in Python without using the list sort() function by using nested for loops. Let us see a few examples, of how we can sort a list without the sort() function.
Sort a List in Ascending Order Without using an Extra Variable
In this example, we will have a list and we will sort it in ascending order using just the nested loop. We will compare each element in the list one by one and swap it.
Python3
l1 = [ 76 , 23 , 45 , 12 , 54 , 9 ]
print ( "Original List:" , l1)
for i in range ( 0 , len (l1)):
for j in range (i + 1 , len (l1)):
if l1[i] > = l1[j]:
l1[i], l1[j] = l1[j],l1[i]
print ( "Sorted List" , l1)
|
Output:
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [9, 12, 23, 45, 54, 76]
Sort a List in Ascending Order by Using an extra variable
In this example, we will have a list and we will sort it in ascending order by using the nested for loop and a temporary variable.
Python3
l1 = [ 76 , 23 , 45 , 12 , 54 , 9 ]
print ( "Original List:" , l1)
for i in range ( 0 , len (l1)):
for j in range (i + 1 , len (l1)):
if l1[i] > = l1[j]:
temp = l1[i]
l1[i] = l1[j]
l1[j] = temp
print ( "Sorted List" , l1)
|
Output:
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [9, 12, 23, 45, 54, 76]
Sort a List in Descending Order
In this example, instead of a predefined list, we will take a list whose values are provided by the user. Then we will sort the list in descending order without using an extra variable.
Python3
l1 = []
n = int ( input ( "enter number of elements required: " ))
for i in range ( 0 , n):
element = int ( input ())
l1.append(element)
print ( "Original List:" , l1)
for i in range ( 0 , len (l1)):
for j in range (i + 1 , len (l1)):
if l1[i] < = l1[j]:
l1[i], l1[j] = l1[j], l1[i]
print ( "Sorted List" , l1)
|
Output:
enter number of elements required: 6
76
23
45
12
54
9
Original List: [76, 23, 45, 12, 54, 9]
Sorted List [76, 54, 45, 23, 12, 9]
Share your thoughts in the comments
Please Login to comment...