Example of using a common sorting algorithm in Python

Source: Internet
Author: User


To prevent misleading readers, all conceptual content in this article is intercepted from the corresponding wiki

Bubble sort

Principle

Bubble sort (Bubble sort) is a simple sort algorithm. It repeatedly visits the sequence to be sorted, compares two elements at a time, and swaps them if their order is wrong. The task of visiting the series is repeated until no further exchange is needed, which means that the sequence has been sorted. The algorithm is named because the smaller elements float slowly through the exchange to the top of the sequence.

Steps

The bubble sort algorithm works as follows:

Compare the adjacent elements. If the first one is bigger than the second one, swap them both.

Do the same work for each pair of adjacent elements, from the first pair to the end of the last couple. After this step, the final element will be the maximum number.

Repeat the above steps for all elements except the last one.

Continue to repeat the previous steps for less and fewer elements until no pair of digits need to be compared.

Code

Def bubble_sort (list):
    length = len (list)
    # First level traversal
     for index in range (length):
        # Second level traversal
         for J in range (1, length-index):
             if LIST[J-1] > list[j]:
                 # Exchanging both data, there is no use of temp because of the Python attribute tuple.
                List[j-1], list[j ] = List[j], list[j-1]
    return list
This sort can actually be optimized a little bit, add a tag, and stop sorting when the sort is finished.

def bubble_sort_flag (list):
length = len (list)
For index in range (length):
# sign Bit
Flag = True
For j in range (1, length-index):
If list[j-1] > List[j]:
List[j-1], list[j] = List[j], list[j-1]
Flag = False
If flag:
# no swap, return directly to list
Return list
Return list

Select sort

Principle

Select sort (Selection sort) is a simple and intuitive sort algorithm. It works by taking the smallest elements of the following element out and placing them sequentially.

Steps

Finds the smallest (large) element in an unordered sequence, and holds it to the starting position of the sort sequence.

Then continue looking for the smallest (large) element from the remaining unordered elements, and then place it at the end of the sorted sequence.

Repeat the second step until all the elements are sorted.

Code

def selection_sort (list):
N=len (list)
For I in Range (0,n):
Min = i
For j in Range (I+1,n):
If List[j]<list[min]:
Min=j
List[min],list[i]=list[i],list[min]
Return list

Insert Sort

Principle

The Insert sort (insertion sort) is a simple and intuitive sort algorithm. It works by building an ordered sequence, scanning the sorted sequence for unsorted data, and finding the location and inserting it.

Steps

Starting with the first element, the element can be thought to have been sorted

Takes out the next element and scans backwards in the sorted sequence of elements

If the element (sorted) is greater than the new element, move the element to the next position

Repeat step 3 until you find where the sorted element is less than or equal to the new element

After inserting the new element into the location

Repeat steps 2~5

Code

def insert_sort (list):
n = len (list)
For I in range (1, N):
# The latter element is compared to the previous element
# if it's smaller than the previous one
If list[i] < List[i-1]:
# Take this number out
temp = List[i]
# Save Subscript
index = i
# to compare each element in turn from the back forward
For j in Range (I-1,-1,-1):
# and exchange the elements larger than the elements
If LIST[J] > Temp:
List[j + 1] = List[j]
index = j
Else
Break
# Insert Element
List[index] = Temp
Return list
Hill sort

Principle

The hill sort, also called the descending increment sorting algorithm, is a more efficient version of the insertion sort. Hill sort is a non stable sort algorithm.

The hill sort is based on the following two-point nature of the insertion order:

The insertion sort is efficient in the operation of data that is almost already sorted, that is, the efficiency of the linear sequencing can be achieved.

However, the insertion sort is generally inefficient because the insertion sort can only move data one bit at a time.

Steps

Sorts each time with a certain step (that is, skipping the equidistant number) until the step is 1.

Code

def shell_sort (list):
n = len (list)
# Initial Step
Gap = Round (N/2)
While Gap > 0:
For I in range (Gap, N):
# Insert Sort each step
temp = List[i]
j = I
# Insert Sort
While J >= Gap and List[j-gap] > Temp:
LIST[J] = List[j-gap]
J-= Gap
LIST[J] = Temp
# Get a new step
Gap = Round (GAP/2)
Return list
The step length is suggested by the Donald Shell, and the step size can also be made using Sedgewick (1, 5,, 109,,...).

You can also use the Fibonacci sequence to remove the number of numbers 0 and 1 that will be counted as twice times the power of the gold partition.

Merge sort

Principle

The merge operation (merging algorithm) refers to the operation of merging two sorted sequences into one sequence. The merge sort algorithm relies on merge operations.

Steps

Iterative method

Application space so that the sum of the two sorted sequences is used to store the merged sequence

Set two pointers, starting at the beginning of two sorted sequences, respectively

Compares the elements pointed to by two pointers, selects the relatively small elements into the merged space, and moves the pointer to the next position

Repeat step 3 until a pointer reaches the end of the sequence

Copy all remaining elements of another sequence directly to the end of the merge sequence

Recursive method

The assumption sequence has a total of n elements:

The sequence is merged with two digits adjacent to each other, forming the {Displaystyle floor (N/2)} floor (N/2) sequence, after which each sequence contains two elements

Merge the above sequence again to form the {Displaystyle floor (N/4)} floor (N/4) sequence, each containing four elements

Repeat step 2 until all the elements are sorted

Code

# recursive method
def merge_sort (list):
# a sequence with a length not greater than 1 is ordered.
If Len (list) <= 1:
Return list
# Two-point list
middle = len (list)//2
left = Merge_sort (List[:middle])
right = Merge_sort (list[middle:])
# last Merge
Return merge (left, right)
# Merging
def merge (left, right):
l,r=0,0
Result=[]
While L<len (left) and R<len (right):
If LEFT[L] <right[r]:
Result.append (Left[l])
L+=1
Else
Result.append (Right[r])
R +=1
Reslut +=left[l:]
Result+=right[r:]
return result
I do not know how to merge sort of iterative method with Python implementation, hope advice.

Quick Sort

Principle

A quick sort uses the divide-and-conquer method (Divide and conquer) strategy to divide a sequence (list) into two sub sequences (sub-lists).

Steps

Pick an element from a series, called a "datum" (pivot),

Reorder the series, all elements smaller than the base value placed in front of the datum, all elements are larger than the base value behind the datum (the same number can be on either side). After the partition is finished, the datum is positioned in the middle of the series. This is called a partition (partition) operation.

recursively (recursive) sorts the substrings that are less than the datum elements and those that are larger than the datum values.

Code

General Edition

def quick_sort (list):
less = []
Pivotlist = []
more = []
# recursive exit
If Len (list) <= 1:
Return list
Else
# make the first value the benchmark
Pivot = list[0]
For I in list:
# put the value of the less into the series
If I < pivot:
Less.append (i)
# put the value of the reference to the more series
Elif i > Pivot:
More.append (i)
# Keep the same values as the Datum in the Datum series
Else
Pivotlist.append (i)
# continue to sort the less series and the more series
less = Quick_sort (less)
more = Quick_sort (more)
Return less + pivotlist +
Cough, the following code is derived from the legendary three lines in the Python Cookbook Second Edition, which implements Python's fast sorting.

def qsort (arr):
If Len (arr) <= 1:
Return arr
Else
Pivot = arr[0]
return Qsort ([x to X in arr[1:] if x < pivot]) + \
[Pivot] + \
Qsort ([x for X in arr[1:] if x >= pivot])
And of course there's a line of grammatical sugars:

QS = lambda xs: ((Len (XS) <= 1 and [XS]) or [QS ([x for X in xs[1:] if x < xs[0]]) + [xs[0]] + QS ([x for x in X S[1:] If x >= xs[0]]) [0]
Do you feel the glamour of python?

Heap Sort

Principle

Heap Ordering (heapsort) is a sort algorithm designed by using the data structure of a heap. Accumulation is the structure of an approximate complete binary tree, and it satisfies the nature of the accumulation: the key value or index of a child node is always less than (or greater than) its parent.

Steps

Create maximum heap: Reorder all data in the heap so that it becomes the largest heap

Maximum heap adjustment: The function is to maintain the maximum heap nature, is to create the largest heap of the Core subroutine

Heap sort: Removes the root node of the first data and does the recursive operation of the maximum heap adjustment

Code

def heap_sort (list):
# Create Maximum Heap
For start in range ((Len (list)-2)//2,-1,-1):
Sift_down (list, start, Len (list)-1)

# heap Sort
For end in range (Len (list)-1, 0,-1):
List[0], list[end] = List[end], list[0]
Sift_down (list, 0, end-1)
Return list


# Max Heap Adjustment
def sift_down (LST, start, end):
Root = Start
While True:
Child = 2 * root + 1
If child > End:
Break
If child + 1 <= end and Lst[child] < Lst[child + 1]:
Child = 1
If Lst[root] < Lst[child]:
Lst[root], Lst[child] = Lst[child], Lst[root]
root = Child
Else
Break
Count sort

Principle

When the input element is an integer between n 0 to K, its elapsed time is theta (n + k). The count sort is not a comparison sort, and the order is faster than any comparison sort algorithm.

Because the length of the array C used to count depends on the range of the data in the array to be sorted (equal to the difference between the maximum and minimum values of the array to be sorted plus 1), this makes the counting order a large amount of time and memory required for a large array of data. For example, a count sort is the best algorithm for sorting numbers between 0 and 100, but it is not appropriate to sort names alphabetically. However, the counting sort can be used in the cardinality sorting algorithm to be more efficient in ordering large arrays of data.

Steps

Find the largest and smallest elements in an array to be sorted

Counts the number of occurrences of an element in an array of I, in the first item of the array C

Add to all counts (starting with the first element in C, and adding each item to the previous item)

To reverse populate the target array: Place each element I in the new array in subparagraph C (i), minus 1 for each element

Code

def count_sort (list):
Min = 2147483647
Max = 0
# Obtain the maximum and minimum values
For x in list:
If x < min:
min = x
If x > Max:
max = X
# Create array C
Count = [0] * (max-min + 1)
For index in list:
Count[index-min] + + 1
index = 0
# Fill in the value
For a in range (max-min+1):
For C in range (Count[a]):
List[index] = a + min
Index + 1
Return list
The Nineth sort of

None?

Of course not

Nature is the system itself.

List.sort ()

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.