• Articles

How to Sort a List in Python Without Using Sort Function

How to Sort a List in Python Without Using Sort Function
Tutorial Playlist

In this guide, we’ll explore methods and code snippets that empower you to sort lists with precision and flexibility, whether you’re organizing contact information, ranking scores, or optimizing data for specific applications.

Table of Contents:

Check out this YouTube video specially designed for Python beginners.

Video Thumbnail

What is Sorting?

Sorting is the process of placing elements or things in a particular order or in a sequence according to some criteria. In the context of computer science and programming, sorting often refers to the arrangement of data components in a certain order, sometimes numerically or alphabetically. The main purpose of sorting is to make it simpler to find, retrieve, or handle data effectively.

The order of the sorting can be either ascending (from smallest to largest) or descending (from largest to smallest). Searching, data analysis, and structuring data for effective retrieval are just a few examples of the many applications where sorting is a basic process in computer science.

There are numerous algorithms and methods for sorting data, each with pros and cons in terms of complexity and performance. These algorithms may be comparison-based sorting, or they may be based on certain characteristics of the data. Popular sorting techniques include quicksort, bubble sort, selection sort, insertion sort, and more.

For developers and data scientists working with huge datasets, sorting is a crucial topic in programming since it facilitates effective data processing and retrieval.

Learn more about Python from this Python Data Science Course to get ahead in your career!

How to Sort List in Python Without Using Sort Function

Even though the sort function is useful and effective, there are times when it’s essential to have a certain amount of control over the sorting order. Programmers can gain flexibility in sorting complex data structures by mastering manual sorting techniques, which allow sorting to be customized for particular requirements.

Developers can choose the sorting approach that is most appropriate for their particular needs by having an in-depth knowledge of the inner workings of sorting algorithms, which develops a deeper understanding of algorithmic complexity and effectiveness. Particularly when working with large data sets, this information is crucial for code optimization and improving overall program efficiency. Programmers are given a valuable skill set when they can sort lists without using the “sort” function, which enables them to address a variety of sorting difficulties with assurance and accuracy.

Being able to sort lists without using the “sort” function gives programmers a useful skill set and enables them to address a variety of sorting difficulties with assurance and accuracy.

Below are some techniques for sorting a list in Python without using the sort function:

Get 100% Hike!

Master Most in Demand Skills Now!

Using For loop 

Ascending Order

# Function to sort a list using for loop
def custom_sort(input_list):
    n = len(input_list)
    for i in range(n):
        for j in range(0, n-i-1):
            if input_list[j] > input_list[j+1]:
                # Swap elements if they are in the wrong order
                input_list[j], input_list[j+1] = input_list[j+1], input_list[j]
# Take a list as input from the user
input_list = input("Enter a list of numbers separated by spaces: ").split()
input_list = [int(x) for x in input_list]  # Convert input to integers
# Call the custom sorting function
custom_sort(input_list)
# Display the sorted list
print("Sorted list:", input_list)

Output:

Enter a list of numbers separated by spaces: 34 56 287 53 99 21 2
Sorted list: [2, 21, 34, 53, 56, 99, 287]

Descending Order

# Predefined list for sorting
my_list = [64, 34, 25, 12, 22, 11, 90]
# Function to sort a list in descending order using for loop
def custom_sort_descending(input_list):
    n = len(input_list)
    for i in range(n):
        for j in range(0, n-i-1):
            if input_list[j] < input_list[j+1]:
                # Swap elements if they are in the wrong order
                input_list[j], input_list[j+1] = input_list[j+1], input_list[j]
# Call the custom sorting function for descending order
custom_sort_descending(my_list)
# Display the sorted list in descending order
print("Sorted list (descending order):", my_list)

Output:

Sorted list (descending order): [90, 64, 34, 25, 22, 12, 11]

Prepare like a pro with our comprehensive Python interview questions and answers guide!

Using While Loop

Ascending Order

# Function to sort a list in ascending order using a while loop
def custom_sort_ascending(input_list):
    n = len(input_list)
    i = 0
    while i < n:
        j = 0
        while j < n - 1:
            if input_list[j] > input_list[j + 1]:
                # Swap elements if they are in the wrong order
                input_list[j], input_list[j + 1] = input_list[j + 1], input_list[j]
            j += 1
        i += 1
# Take a list as input from the user
input_list = input("Enter a list of numbers separated by spaces: ").split()
input_list = [int(x) for x in input_list]  # Convert input to integers
# Call the custom sorting function for ascending order
custom_sort_ascending(input_list)
# Display the sorted list in ascending order
print("Sorted list (ascending order):", input_list)

Output:

Enter a list of numbers separated by spaces: 23 56 89 33 56 21 78 45 93
Sorted list (ascending order): [21, 23, 33, 45, 56, 56, 78, 89, 93]

Descending Order

# Predefined list for sorting in descending order
my_list_descending = [64, 34, 25, 12, 22, 11, 90]
# Function to sort a list in descending order using a while loop
def custom_sort_descending(input_list):
    n = len(input_list)
    i = 0
    while i < n:
        j = 0
        while j < n - 1:
            if input_list[j] < input_list[j + 1]:
                # Swap elements if they are in the wrong order
                input_list[j], input_list[j + 1] = input_list[j + 1], input_list[j]
            j += 1
        i += 1
# Call the custom sorting function for descending order
custom_sort_descending(my_list_descending)
# Display the sorted list in descending order
print("Sorted list (descending order):", my_list_descending)

Output:

Sorted list (descending order): [90, 64, 34, 25, 22, 12, 11]

Using Slicing

Ascending Order 

arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = []
while arr:
    minimum = min(arr)  # Find the minimum element
    sorted_arr.append(minimum)
    arr = arr[:arr.index(minimum)] + arr[arr.index(minimum) + 1:]
print("Sorted list (ascending):", sorted_arr)

Output:

Sorted list (ascending): [11, 12, 22, 25, 34, 64, 90]

Descending Order

# Take a list as input from the user
input_list = input("Enter a list of numbers separated by spaces: ").split()
input_list = [int(x) for x in input_list]  # Convert input to integers
sorted_list = []
while input_list:
    maximum = max(input_list)  # Find the maximum element
    sorted_list.append(maximum)
    input_list = input_list[:input_list.index(maximum)] + input_list[input_list.index(maximum) + 1:]
print("Sorted list (descending):", sorted_list)

Output:

Enter a list of numbers separated by spaces: 78 46 82 37 91 23 45
Sorted list (descending): [91, 82, 78, 46, 45, 37, 23]

Using ‘pop’ Method

Ascending Order

arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = []
while arr:
    minimum = min(arr)  # Find the minimum element
    sorted_arr.append(minimum)
    arr.pop(arr.index(minimum))
print("Sorted list (ascending):", sorted_arr)

Output:

Sorted list (ascending): [11, 12, 22, 25, 34, 64, 90]

Descending Order

# Take a list as input from the user
input_list = input("Enter a list of numbers separated by spaces: ").split()
input_list = [int(x) for x in input_list]  # Convert input to integers
sorted_list = []
while input_list:
    maximum = max(input_list)  # Find the maximum element
    sorted_list.append(maximum)
    input_list.pop(input_list.index(maximum))
print("Sorted list (descending):", sorted_list)

Output:

Enter a list of numbers separated by spaces: 85 46 25 79 165 7 3 8 
Sorted list (descending): [165, 85, 79, 46, 25, 8, 7, 3]

Get ready for the high-paying Data Scientist jobs with these Top Data Science Interview Questions and Answers!

Advance Techniques for Sorting

Below are the sorting algorithms that have their own benefits and drawbacks in terms of complexity and efficiency. The sorting method you choose will rely on the details of your work and the properties of the data you need to sort.

Bubble Sort: Bubble Sort is an algorithm that iteratively traverses the list, compares nearby members, and swaps out any that are out of order. It keeps on until the list has been sorted.

Selection Sort: Selection Sort locates the minimum element from the list’s unsorted section and replaces it with the unsorted section’s first element. The list gets sorted completely once this step is finished.

Insertion Sort: This sorting technique gradually creates a sorted segment of the list. It moves each element from the unsorted portion into the appropriate spot in the sorted area one at a time.

Merge Sort: Divide-and-conquer strategy is used in the merge sort algorithm. The list is broken up into smaller sublists, sorted separately, and then brought back together as one sorted list.

Quick Sort: Another divide-and-conquer method is Quick Sort, which chooses a “pivot” element and divides the list into two sublists: one with elements below the pivot and the other with elements above the pivot. After that, it sorts the sublists iteratively.

Heap Sort: To construct a sorted list, Heap Sort builds a heap using a binary heap data structure and repeatedly extracts the most elements (in ascending order).

Counting Sort: This method works well for sorting integers that fall within a certain range. Following the reconstruction of a sorted list, it counts the instances of each integer in the list.

Radix Sort: Integer sorting is appropriate for Radix Sort. It organizes the list by processing each digit individually, going from least to most important.

End-Note

Learning how to sort lists in Python without using the built-in ‘sort’ function opens the door to a world of specialized data manipulation. This ability is extremely useful in real-world situations, such as setting up huge databases of client information for targeted advertising or simplifying inventory control procedures for companies. Programmers have the ability to create solutions that are customized to individual requirements and increase overall program efficiency by understanding the inner workings of sorting algorithms. In the world of data-driven decision-making and application development, the ability to sort lists with accuracy and control is a key asset, whether it’s for improving search operations on a website or sorting crucial financial data for investment research.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch