SoFunction
Updated on 2024-11-16

Python implementation of the quick sort and insertion sort algorithms and examples of custom sorting

I. Rapid sorting

Quicksort is an improvement on bubble sort. It was proposed by C. A. R. Hoare in 1962. Its basic idea is: through a sort to be sorted data is divided into two independent parts, one of the part of all the data are smaller than the other part of all the data, and then according to the method of these two parts of the data are quickly sorted, the whole sorting process can be recursive, so as to achieve the whole data into an ordered sequence.

Quick sort, recursive implementation

def quick_sort(num_list):
  """
  Rapid Sorting
  """
  if num_list == []:
    return num_list
  smallList = []
  bigList = []
  middleElement = num_list[0]
  for i in num_list[1:]:
    if i <= middleElement:
      (i)
    else:
      (i)
  return quick_sort(smallList)+[middleElement]+quick_sort(bigList)


II. Insertion Sort

The algorithm description of Insertion Sort is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence, and for unsorted data, scanning backward and forward through the sorted sequence to find the appropriate position and insert it. Insertion Sort is usually implemented as an in-place sort (i.e., a sort that uses only O(1) of extra space), and thus in the back-to-front scanning process, it is necessary to repeatedly move the sorted elements backward step by step to provide insertion space for the newest element.

insertion sort

def insert_sort(num_list):
  """
  Insertion Sorting
  """
  for i in range(len(num_list)-1):
    for j in range(i+1, len(num_list)):
      if num_list[i]>num_list[j]:
        num_list[i],num_list[j] = num_list[j],num_list[i]
  return num_list


III. Customized sorting
This is achieved by using the key of sort() or sorted().

Examples are shown below:

def sort_key(obj):
  sorted_list = [4, 2, 5, 9, 7, 8, 1, 3, 6, 0]
  return sorted_list.index(obj)
 
 
if __name__ == '__main__':
  print sorted(range(10), key=sort_key)
 
# The output is as follows
[4, 2, 5, 9, 7, 8, 1, 3, 6, 0]

 
# Customized sorting using the index position of the keyword in the list