To sort a list of numbers in Python without a sort function, you can define your own function and loop through the list swapping numbers based on their values.
def sort_without_sort(lst):
for i in range(0, len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst
print(sort_without_sort([9,2,5,4,1,0,7,5]))
#Output:
[0, 1, 2, 4, 5, 5, 7, 9]
When working with collections of data in Python, the ability to easily be able to sort and order the data in the way we want is very valuable.
One such case is if you want to sort a list of numbers.
There are built-in functions such as sort() and sorted() that allow you to sort collections of data in Python, but you can also define your own function which will sort a list of numbers.
To sort numbers in Python without the sort() function, the key is to create a function which will loop over each number and compare each number to every other number in the list. Then at each iteration, we compare the two numbers and swap them if they are out of order.
Below is a user-defined function which will sort a list of numbers in Python.
def sort_without_sort(lst):
for i in range(0, len(lst)):
for j in range(i + 1, len(lst)):
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst
print(sort_without_sort([9,2,5,4,1,0,7,5]))
#Output:
[0, 1, 2, 4, 5, 5, 7, 9]
If you want to add the ability for the user to sort the list of numbers ascending or descending, we can add another argument and an if statement in the inner loop.
def sort_without_sort(lst, desc):
for i in range(0, len(lst)):
for j in range(i + 1, len(lst)):
if desc:
if lst[i] < lst[j]:
lst[i], lst[j] = lst[j], lst[i]
else:
if lst[i] > lst[j]:
lst[i], lst[j] = lst[j], lst[i]
return lst
print(sort_without_sort([9,2,5,4,1,0,7,5], False))
print(sort_without_sort([9,2,5,4,1,0,7,5], True))
#Output:
[0, 1, 2, 4, 5, 5, 7, 9]
[9, 7, 5, 5, 4, 2, 1, 0]
Hopefully this article has been useful for you to learn how to sort numbers in Python without the sort() function.
Leave a Reply