Python implementation of common sorting algorithms

Source: Internet
Author: User
Tags for in range

This article introduces several kinds of commonly used sorting algorithms, including bubble sort, select sort, insert sort, merge sort, quick sort, heap sort, the code involved in this article can be found on Https://github.com/lianyingteng/Programming-practice

1. Bubble sort

Time complexity O (n^2), stable sorting algorithm

ideas: The first comparison of the interval is "0,n-1", in order to compare adjacent two, which number is the number of which is placed in the back, so that once the array, the largest number will be in the last position of the array, and then the comparison interval from "0,n-1" narrowed to "0,n-2", After a traversal, the second largest number is placed in the second-to-last position of the array, and so on. The array is ordered until the range is narrowed down to a number.

def Bubblesort (arr):    
= len (arr) for in range (length-1# number of times for in range (length-i-1# number of elements per trip if arr[j] > arr[j+1 ]: arr[j], arr[j+1] = arr[j+1], arr[j] return arr
2. Select sort

Time complexity O (n^2), unstable sorting algorithm

idea: start from "0,n-1" to choose a minimum value placed on position 0, the second time from "1,n-1" on the selection of a minimum value placed on position 1, and so on; until the array accesses the remaining element, the array is ordered.

defSelectionsort (arr):"""Select Sort"""length=Len (arr) forIinchRange (length): Min_i= I#Minimum Value Index         forJinchrange (i, length):ifArr[min_i] >Arr[j]: Min_i=J Arr[min_i], Arr[i]=Arr[i], Arr[min_i]returnArr
3. Insert Sort *

Time complexity O (n^2), stable sorting algorithm

Note : When the array is almost ordered, the time complexity is O (n*k), K is the most moving distance, and when the array is reversed, the time complexity is Max O (n^2)

idea: the n order of elements to be sorted as an ordered table and an unordered table, the beginning of the ordered table only one element, unordered table has n-1 elements. Each time the sorting process takes an element out of the unordered table, the sorting code is compared with the elements in the ordered table (before and after), inserting it into the proper position of the ordered table and making it a new ordered table.

defInsertsort (arr):"""Insert Sort"""length=Len (arr) forIinchRange (length-1): O_i= I#index of the last element of an ordered tableU_v = arr[o_i+1]#element values for unordered tables                 whileO_i >= 0 andArr[o_i] >u_v:arr[o_i+1] =Arr[o_i] O_i-= 1arr[o_i+1] = U_v#with the insertion element in the appropriate position, +1 is because the front-1    returnArr
4. Merge Sort *

Time complexity O (NLOGN), stable sorting algorithm

idea: first let each element of the array be an ordered interval of length 1, then merge the two ordered intervals of length 1, generate an ordered interval of 2 length, and then merge the ordered intervals of two length 2 to produce an ordered interval of length 4, and so on until the array is ordered. 1 in 2, 2 in 4, 4 in 8, 8in .....

defMergersort (arr):"""the merge sort divides into the left and right two parts; 22 merges into an ordered array"""    ifLen (arr) <= 1:        returnarr Mid= Len (arr)//2#divide left and right, generate an ordered array of length 1 to start returningLeftarr =Mergersort (Arr[:mid]) Rightarr=Mergersort (arr[mid:])#22 Merging    returnmerger (Leftarr, Rightarr)defmerger (left, right):"""merges two sequential arrays to form a new ordered array return"""Res=[] L, R=0, 0 whileL < Len (left) andR <Len (right):ifLEFT[L] <=Right[r]: Res.append (Left[l]) L+ = 1Else: Res.append (Right[r]) R+ = 1Res+=Left[l:] Res+=Right[r:]returnRes
5. Quick Sort * *

Time complexity O (NLOGN), unstable sorting algorithm

Note : In the case of complete unordered array, the NLOGN is the best, O (n/a), and the worst effect in order, O (n^2).

idea: random sort-randomly select a number in an array so that the number of the array greater than it is placed on its right, less than or equal to its number on its left, and then the left and right sides of the number recursively call the process of the fast.

one-time partitioning of the quick -order process-the complexity of the Times is O (n):

First, we randomly select one of the arrays as the dividing value, then we swap the dividing value with the last element of the array so that the dividing value is placed in the last position of the array (for example, B), and then we define a less than or equal interval , initially, less than or equal to the interval is empty, On the leftmost side of the array (for example, C), and then start traversing the array, if the element is greater than the dividing value, continue to traverse the next element, if the element value is less than or equal to the dividing value, let the element be swapped with the next element less than or equal to the interval ( e.g. d,e) , perform this procedure sequentially until only one number is left in the array, and then the last number of the array (the partition value) is exchanged with the next number less than or equal to the interval, and the one-time division of the queue ends ( such as F,g).

defQuickSort (arr, left, right):"""fast sorting of arrays on left to right interval"""    ifLeft >=Right :returnNone Midvalue= arr[(left+right)//2]#Dividing valuesL, R =Left , right whileL <r: whileArr[l] < Midvalue:l + = 1 whileARR[R] > Midvalue:r-= 1ifL >= R: BreakArr[l], Arr[r]=Arr[r], Arr[l] r-= 1L+ = 1ifL = =r:l+ = 1R-= 1ifLeft <R:quicksort (arr, left, R)ifRight >L:quicksort (arr, L, right)returnNone
6. Heap Sequencing

Time complexity: O (NLOGN), an unstable sorting algorithm, often used to find top X

idea: first build a large heap of all the elements on the array "0,n-1" interval, and then swap the top elements of the heap with the last element of the array, so that the last element of the array is the maximum value, as an ordered part of the array, and then the array "0,n-2" All elements on the interval are constructed into a large heap, and then the top element of the heap is swapped with the second-to-last element of the array, so that the two-bit elements of the array are the maximum and second largest values of the array, and then the array interval "0,n-3" is built into a large heap, exchanged;

defHeapsort (arr):"""Heap Sort"""arr=buildmaxheap (arr) forIinchList (len (arr))) [::-1]: arr[0], Arr[i]=Arr[i], arr[0] adjustheap (arr, 0, i)#n Indicates the size of the array (not the heap)    returnarrdefbuildmaxheap (arr):"""Build Dagen build from bottom up"""     forIinchList (range len (arr)//2)) [::-1]: adjustheap (arr, I, Len (arr))returnarrdefadjustheap (arr, start, size):"""the array [start:] Adjusts the pile structure parameters---start:int array start index Size:int Array size"""Lchild= 2 * start + 1Rchild= 2 * start + 2Maxi=StartifMaxi < size//2:#It means having kids .        ifLchild < size andArr[lchild] >Arr[maxi]: Maxi=LchildifRchild < size andArr[rchild] >Arr[maxi]: Maxi=RchildifMaxi! = Start:#= = Description is already the largest heap, so this is notArr[maxi], Arr[start] =Arr[start], Arr[maxi] Adjustheap (arr, maxi, size)

Python implementation of common sorting algorithms

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.