Sorting Algorithms in Programming: Types, Descriptions, and Comparisons

0
(0)

We’ll look at code examples and choose the fastest and most convenient approaches.

Sorting algorithms help programmers organize data and provide quick access—and thus speed up the development and operation of future services. We’ll discuss several algorithms that can be used in Python.

Why do we need sorting algorithms?

Imagine a large box filled with coins of various denominations from all over the world. You need to find 100 Japanese yen. In such a chaotic environment, you’ll likely have to sort through every coin that matches the one you’re looking for. This will take a lot of time and effort. The easiest way to speed up the process is to sort all the coins into small boxes, assigning a separate place for each currency.

Now the search will be significantly faster, since we know exactly where all the yen are. But there’s always room for improvement, so we can improve the search even further. Now, in a box with yen, you can sort all the coins of the same denomination into separate envelopes. So, finding 100 Japanese yen comes down to two steps: finding the box with the yen, and then finding the envelope with the desired denomination inside.

Sorting has allowed us to optimize coin storage and speed up the search for the right one. Furthermore, we can now accurately predict the number of steps required to find any coin and calculate the approximate time. Sorting through everything at once won’t give you such accurate results before you even start searching. You might pull out the right coin on the first try, or you might search through the entire box and discover it’s not there.

Sorting in programming also helps optimize data storage, speed up information retrieval, predict complex operations, and conserve resources. However, there is a wide range of sorting algorithms of varying complexity and speed, each with its own pros and cons.

Bubble sort

This is the simplest and most well-known method for sorting array elements. However, it’s also the least efficient algorithm, taking a long time to execute. The difference in time is difficult to notice with small arrays, but if there’s a lot of data, sorting will take a long time. Bubble sort performs particularly poorly on arrays with small elements at the very end.

The essence of the algorithm is to sequentially compare the values ​​of adjacent array elements. If the next element is smaller than the current one, we swap them. This process must be repeated until the array elements are in their proper order. If you reach the end of the array and the data is not yet sorted, you must start over.

The Python implementation of the bubble sort algorithm looks like this:

def bubble_sort ( arr ) :
n = len ( arr )
# The outer loop iterates through all the elements of the array
for i in range ( n – 1 ) :
# The inner loop goes from 0 to ni-1
for j in range ( 0 , n – i – 1 ) :
# Compare adjacent elements
if arr [ j ] > arr [ j + 1 ] :
# If the current element is greater than the next one, swap them
arr [ j ] , arr [ j + 1 ] = arr [ j + 1 ] , arr [ j ]
return arr
unsorted_list = [ 64 , 25 , 12 , 22 , 11 ]
sorted_list = bubble_sort ( unsorted_list )
print ( “Sorted list:”, sorted_list )

Now let’s try to sort a small array using it:

unsorted_list = [ 64 , 25 , 12 , 22 , 11 ]
sorted_list = bubble_sort ( unsorted_list )
print ( sorted_list )
>>> [ 11 , 12 , 22 , 25 , 64 ]

We were able to sort the array, but it’s important to remember that the execution time of such a sort is equally poor in all cases. This will be especially noticeable with large data sets.

Cocktail sort

Shuffle sort is sometimes called bidirectional or shaker sort. The algorithm is an improved version of bubble sort that addresses the last element problem. For example, if the smallest element is at the end of the array, it will only shift one position on each iteration.

To solve this problem, shuffle sort iterates through the array twice, alternating direction. First, the algorithm starts at the beginning of the array, comparing pairs of adjacent elements. They are swapped if the element on the left is larger than the element on the right. If we reach the end, we reverse direction and return to the beginning. In this case, smaller elements are moved to the left. The algorithm continues until all elements are in their correct order.

The main advantage of shuffle sort is that it reduces the number of sorting iterations. Despite this advantage, the algorithm remains slow and performs poorly on large data sets.

The Python implementation of the shuffle sort algorithm looks like this:

def cocktail_sort ( arr ) :

n = len ( arr )
# Initializing variables for array bounds
start = 0
end = n – 1
while start < end:
# Left to right traversal, similar to bubble sort
for i in range ( start, end ) :
if arr [ i ] > arr [ i + 1 ] :
# If the current element is greater than the next one, swap them
arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ]
# Reduce the right border since the largest element is already in the correct position
end -= 1
# Passage from right to left
for i in range ( end – 1 , start – 1 , -1 ) :
if arr [ i ] > arr [ i + 1 ] :
# If the current element is greater than the next one, swap them
arr [ i ] , arr [ i + 1 ] = arr [ i + 1 ] , arr [ i ]
# We increase the left border, since the smallest element is already in the correct position
start += 1
return arr

Now let’s try to sort a small array using it:

unsorted_list = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ]
sorted_list = cocktail_sort ( unsorted_list )
print ( sorted_list )
>>> [ 11 , 12 , 22 , 25 , 34 , 64 , 90 ]

Insertion sort

The sorting method divides the array into two parts: the sorted part and the common part. At the beginning of the algorithm, the first element of the array is assumed to be in its proper position. Therefore, the array is examined starting with the second element and continues until all elements in the sorted part are in their proper positions.

Insertion sorting looks like this step by step:

  • The first element is considered sorted, and the entire array is divided into two parts. The first part contains the first element, and the rest is the unsorted part.
  • The first element from the unsorted part is taken.
  • The selected element is placed in the correct position in the sorted part, and the remaining elements in it are shifted.

The last two steps repeat in a loop: take an element, find its location, and repeat. Ultimately, all elements should be included in the sorted portion of the array. Insertion sort works well on small data sets. It can also be used in conjunction with other sorting methods to optimize execution time.

The Python implementation of the insertion sort algorithm looks like this:

def insertion_sort ( arr ) :
# Get the length of the array
n = len ( arr )
# We start with the second element, since we assume that the first element is already sorted
for i in range ( 1, n ) :
# The current element we are going to insert into the sorted part of the array
key = arr [ i ]
# Index of the previous element in the sorted part of the array
j = i – 1
# Move all elements greater than key one position forward
# Until we find the correct place to insert the key or reach the beginning of the array
while j > = 0 and key < arr [ j ] :
arr [ j + 1 ] = arr [ j ]
j -= 1
# Insert the key into the correct place in the sorted part of the array
arr [ j + 1 ] = key
return arr

Now let’s try to sort a small array using it:

unsorted_list = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ]
sorted_list = insertion_sort ( unsorted_list )
print ( sorted_list )
>>> [ 11 , 12 , 22 , 25 , 34 , 64 , 90 ]

Selection sort

The selection sort algorithm also divides the array into two arbitrary parts: sorted and unsorted. However, the minimum element is used for insertion, not the first element of the unsorted part. It is then inserted at the beginning of the sorted part.

Selection sorting, step by step, looks like this:

  • The element with the minimum value is selected from the unsorted part.
  • This element is swapped with the first element in the array.
  • The search in the unsorted part starts again, but the already sorted elements do not take part in it.

The steps are performed in a loop until all array elements are in their correct order. If you need to sort the data in reverse order, you should search for the maximum elements instead of the minimum ones. It’s important to note that selection sort is ineffective in large arrays. However, there are advantages: the algorithm takes little time to implement.

The implementation of the selection sort algorithm in Python looks like this:

def selection_sort ( arr ) :
n = len ( arr )
# We go through all the elements of the array
for i in range ( n ) :
# Index of the minimum element in the unsorted part of the array
min_index = i
# Find the minimum element in the unsorted part of the array
for j in range ( i + 1 , n ) :
if arr [ j ] < arr [ min_index ] :
min_index = j
# Exchange the minimum element with the first element of the unsorted part
arr [ i ] , arr [ min_index ] = arr [ min_index ] , arr [ i ]
return arr

Now let’s try to sort a small array using it:

unsorted_list = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ]
sorted_list = selection_sort ( unsorted_list )
print ( sorted_list )
>>> [ 11 , 12 , 22 , 25 , 34 , 64 , 90 ]

Quicksort

This is one of the fastest and most versatile sorting algorithms. The algorithm was developed by the English mathematician Tony Hoare in 1960, while working at Lomonosov Moscow State University. The algorithm is based on the divide-and-conquer principle, which implies that a task should be divided into two identical subtasks. Quicksort is the algorithm most often used in real-world projects.

To begin quicksort, a pivot element must be selected. This is most often one of the outermost elements, but a random selection is also possible. The value of the pivot element itself will not affect the speed of the operation. The array is then divided into two halves: elements smaller than the pivot are moved to the left, and elements larger than the pivot are moved to the right. Then, we recursively divide and sort each half until they reach a minimum size.

The Python implementation of the quicksort algorithm looks like this:

def quicksort ( arr ) :
if len ( arr ) < = 1 :
return arr # Base case: If the array contains 1 element or less, it is already sorted
pivot = arr [ len ( arr ) // 2 ] # Selecting the pivot element
# Splitting an array into three parts: elements less than, equal to, and greater than the reference
left = [ x for x in arr if x < pivot ]
middle = [ x for x in arr if x == pivot ]
right = [ x for x in arr if x > pivot ]
# Recursively combine results
return quicksort ( left ) + middle + quicksort ( right )

Now let’s try to sort a small array using it:

unsorted_list = [ 64 , 34 , 25 , 12 , 22 , 11 , 90 ]
sorted_list = quicksort ( unsorted_list )
print ( sorted_list )
>>> [ 11 , 12 , 22 , 25 , 34 , 64 , 90 ]

Experienced programmers, what sorting algorithms do you use? Share your thoughts in the comments; it’ll be very helpful for beginners.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email
CONTINUE LEARNING Next: Algorithm →

Leave a Reply

Your email address will not be published. Required fields are marked *