Python implementation of eight sort algorithms and eight sort algorithms python

Source: Internet
Author: User

Python implementation of eight sort algorithms and eight sort algorithms python

Python implements eight sorting algorithms. The specific content is as follows:

1. Insert sorting
Description

The basic operation of insert sorting is to insert a data to an ordered data that has been sorted in order to obtain a new ordered data with a number plus one. The algorithm is applicable to sorting a small amount of data, the time complexity is O (n ^ 2 ). Is a stable sorting method. The insert algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except the last element (so that the array can have more space to insert ), the second part only contains this element (that is, the element to be inserted ). After sorting the first part, insert the last element to the first part of the sorted part.

Code Implementation

Def insert_sort (lists): # insert sort count = len (lists) for I in range (1, count ): key = lists [I] j = I-1 while j> = 0: if lists [j]> key: lists [j + 1] = lists [j] lists [j] = key j-= 1 return lists

2. Hill sorting
Description

Shell Sort is a Sort of insert. Also known as downgrading incremental sorting, it is a more efficient and improved version that directly inserts the sorting algorithm. Hill sorting is a non-stable sorting algorithm. This method was named after DL. Shell was proposed in 1959. Hill sorting refers to the incremental grouping of records by the subject, and the direct insertion sorting algorithm is used for sorting each group. As the increment decreases gradually, each group contains more and more keywords. When the increment is reduced to 1, the entire file is divided into a group, and the algorithm is terminated.

Code Implementation

Def shell_sort (lists): # Hill sort count = len (lists) step = 2 group = count/step while group> 0: for I in range (0, group ): j = I + group while j <count: k = j-group key = lists [j] while k> = 0: if lists [k]> key: lists [k + group] = lists [k] lists [k] = key k-= group j + = group/= step return lists

3. Bubble Sorting
Description

It repeatedly visits the series to be sorted, compares two elements at a time, and exchanges them if their order is wrong. The work of visiting a sequence is repeated until there is no need for exchange, that is, the sequence has been sorted.

Code Implementation

Def bubble_sort (lists): # bubble sort count = len (lists) for I in range (0, count): for j in range (I + 1, count ): if lists [I]> lists [j]: lists [I], lists [j] = lists [j], lists [I] return lists

4. Fast sorting
Description

Data to be sorted is divided into two independent parts by one sort. All the data in one part is smaller than all the data in the other part, then, sort the two data parts by using this method. The entire sorting process can be recursive to convert the entire data into an ordered sequence.

Code Implementation

Def quick_sort (lists, left, right): # Quick sorting if left> = right: return lists key = lists [left] low = left high = right while left <right: while left <right and lists [right]> = key: right-= 1 lists [left] = lists [right] while left <right and lists [left] <= key: left + = 1 lists [right] = lists [left] lists [right] = key quick_sort (lists, low, left-1) quick_sort (lists, left + 1, high) return lists

5. Directly select sorting
Description

Basic Idea: 1st times, record r1 ~ in waiting for sorting ~ Select the smallest record from r [n] and exchange it with r1. For example, 2nd rows, record r2 ~ Select the smallest record in r [n] and exchange it with r2. Similarly, the I-th record is in the record to be sorted r [I] ~ Select the smallest record in r [n] and exchange it with r [I] so that the ordered sequence continues to grow until all the records are sorted.

Code Implementation

Def select_sort (lists): # select sort count = len (lists) for I in range (0, count): min = I for j in range (I + 1, count ): if lists [min]> lists [j]: min = j lists [min], lists [I] = lists [I], lists [min] return lists

6. Heap sorting
Description

Heapsort is a sort algorithm designed by using the data structure of the stacked tree (Heapsort. You can use the features of arrays to quickly locate the elements of a specified index. The heap is divided into a large heap and a small heap, which is a complete binary tree. The requirement of A large root heap is that the value of each node is not greater than that of its PARENT node, that is, A [PARENT [I]> = A [I]. In the non-descending sorting of arrays, you need to use the big root heap, because according to the requirements of the big root heap, the maximum value must be at the top of the heap.

Code Implementation

# Adjust the heap def adjust_heap (lists, I, size): lchild = 2 * I + 1 rchild = 2 * I + 2 max = I if I <size/2: if lchild <size and lists [lchild]> lists [max]: max = lchild if rchild <size and lists [rchild]> lists [max]: max = rchild if max! = I: lists [max], lists [I] = lists [I], lists [max] adjust_heap (lists, max, size) # create heap def build_heap (lists, size): for I in range (0, (size/2) [:-1]: adjust_heap (lists, I, size) # heap sorting def heap_sort (lists ): size = len (lists) build_heap (lists, size) for I in range (0, size) [:-1]: lists [0], lists [I] = lists [I], lists [0] adjust_heap (lists, 0, I)

7. Merge and sort
Description

Merge Sorting is an effective Sorting Algorithm Based on merge operations. This algorithm is a typical application of Divide and Conquer. Merges ordered subsequences to obtain a fully ordered sequence. That is, first orders each subsequence, and then orders the subsequence segments. If two ordered tables are merged into an ordered table, it is called a two-way merge.

The merging process is: Compare the sizes of a [I] And a [j]. If a [I] is less than or equal to a [j], copy the element a [I] In the first ordered table to r [k] and Add 1 to I and k respectively; otherwise, copy the element a [j] In the second ordered table to r [k], and Add 1 to j and k respectively. In this way, the loop continues until one of the ordered tables is completed, then copy the remaining elements in another ordered table to the Unit from subscript k to subscript t in r. The Merge Sorting Algorithm is implemented recursively. We first sort the subintervals [s, t] to the midpoint, then sort the left subintervals, and then sort the right subintervals, finally, merge the left and right intervals into an ordered interval [s, t] with one merge operation.

Code Implementation

Def merge (left, right): I, j = 0, 0 result = [] while I <len (left) and j <len (right ): if left [I] <= right [j]: result. append (left [I]) I + = 1 else: result. append (right [j]) j + = 1 result + = left [I:] result + = right [j:] return resultdef merge_sort (lists ): # merge and sort if len (lists) <= 1: return lists num = len (lists)/2 left = merge_sort (lists [: num]) right = merge_sort (lists [num:]) return merge (left, right)

8. Base sorting
Description

Base sorting (radix sort) is a type of "distribution sort", also known as "bucket sort" or "bin sort". As the name suggests, it uses some information about key values, elements to be sorted are allocated to certain "buckets" to achieve sorting. The base sorting method is a stable sorting, and its time complexity is O (nlog (r) m ), r indicates the base number adopted, while m indicates the number of heaps. In some cases, the base sorting method is more efficient than other stability sorting methods.

Code Implementation

import mathdef radix_sort(lists, radix=10):  k = int(math.ceil(math.log(max(lists), radix)))  bucket = [[] for i in range(radix)]  for i in range(1, k+1):    for j in lists:      bucket[j/(radix**(i-1)) % (radix**i)].append(j)    del lists[:]    for z in bucket:      lists += z      del z[:]  return lists

The above is a detailed introduction to Python's implementation of the eight sorting algorithms. I hope this will help you learn more.

Articles you may be interested in:
  • Insert Sorting Algorithm in python
  • Python Merge Sorting Algorithm
  • Python implements heap sorting algorithm code
  • Various Sorting Algorithm codes implemented by python
  • Python insert Sorting Algorithm Implementation Code
  • Python implementation code for sorting algorithm selection
  • Python Bubble Sorting Algorithm Implementation Code
  • Examples of several common sorting algorithms implemented by Python

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.