Python implementation method and principle of some sort algorithms

Source: Internet
Author: User

Today, a question suddenly comes to mind: will you immediately write out the sorting algorithm for the heap platoon, the fast platoon, etc., and not make a logical mistake?

I said: No, at least you need to think about it, and it may take time to debug.

Before I always think, is not the sorting algorithm? What's the big deal? On the Internet, the book is a lot of search. But a different angle: Will you?

Sorting algorithm should be as the most basic tool, is handy pinch, so I put "introduction to the algorithm," a few sort of problems to see and realize it again; here to share:

Bubble Sort:

Bubble sort is a relatively simple and widely used sort algorithm, but its efficiency is not very high, we can first look at the implementation of:

defBubblesort (A): Length= LenA;     forIinch Range(0, length): forJinch Range(length- 1I-1):ifA[J]<A[j- 1]: (A[j], a[j- 1])=(A[j- 1], A[j]);    returnA;A=[5,0,1,3,6,2,4,9, A, One, -, -,7,8, +, -, -, -, -,Ten];A=Bubblesort (a);Print(a);

As the name implies, bubbling sort is like a bubble layer to the top, need a comparison;
The number of comparisons (n-1)N/2, the worst case of data exchange times 3(n-1) *N/2, the best case 0, so its time complexity O (n^2);

Insert Sort:
defInsertionsort (A): forIinch Range(1,Len(A)): Key=A[i];J=I- 1;         while(j>= 0) and(A[j]>Key): A[j+ 1]=A[J];J=J- 1;A[j+1]=Key;    returnA;A=[5,0,1,3,6,2,4,9, A, One, -, -,7,8, +, -, -, -, -,Ten];A=Insertionsort (a);Print(a);

To understand the insertion sort, you can imagine how to take a card when playing poker, we touch a card, and then from left to right (or from right to left) in order to compare, then the card into the corresponding position, insert sort is the idea.
Time complexity O (n^2)

Merge sort:

Remember sophomore study "Data Structure" for the first time to write this algorithm thought for a long time, because the use of recursive ideas, some places always can not turn the bend.

defMerge (A): Length= LenA;    ifLength<= 1:returnA;N1=Length/ 2;N2=Length-N1;L=[];R=[];     forIinch Range(0, N1): L.append (A[i]);     forIinch Range(0, N2): R.append (a[n1+I]);    ifN1> 1: Merge (L);    ifN2> 1: Merge (R);I= 0;J= 0;     forKinch Range(0, length):ifL[i]<R[J]: a[k]=L[i];I=I+ 1;            ifI>=N1: forIinch Range(J, N2): K=K+ 1;A[K]=R[i];                 Break;        Else: A[k]=R[J] J=J+ 1;            ifJ>=N2: forJinch Range(I, N1): K=K+ 1;A[K]=L[J];                 Break;    returnA;A=[5,0,1,3,6,2,4,9, A, One, -, -,7,8, +, -, -, -, -,Ten];A=Merge (a);Print(a);

If you can understand the idea of recursion well, it is easy to merge the sort. The core idea is how to break the problem down into a series of small problems. We can think of it this way:
How do two sequential sequences merge into a sequence?

Two sequences of data one by one comparison, will be small into the new queue, until the two series of one is empty, then another sequence of remaining data into the queue. If you think of these two series as poker, you might understand better. If both of these sequences have only one data, will it be very simple to finish the line?

[1, 3, 5], [2, 4, 6, 7] ======> [1, 2, 3, 4, 5, 6, 7]

Merge sort by recursive method, a sequence of columns to be sorted is eventually replaced by a number of sequences containing one data.

Time Complexity O (Nlog (n))

Heap Sort:

Once, the first time to write a heap row, with C linked list, confidently built a two-pronged tree! The original heap sort does not need to build a visual two-fork tree!!! The use of the original order (only the subscript and corresponding elements) to solve!!!

Parent= LambdaI: (i-  1)/ 2;Left= LambdaI2 *I+ 1;Right= LambdaI2 *I+ 2;Exchange= LambdaA, B: (b, a);defMaxheapfy (A, I, length): l=Left (i);R=Right (i);    ifL<Length andA[L]>A[i]: Large=L;    Else: Large=I;    ifR<Length andA[R]>A[large]: Large=R;    ifLarge!=I: (A[i], A[large])=Exchange (A[i], A[large]);Maxheapfy (A, large, length);    returnA;defBuildheap (A, length): forIinch Range(length/ 2 - 1,-1,-1): Maxheapfy (A, I, length);defHeapsort (A): Length= LenA;Buildheap (A, length);     forIinch Range(LenA- 1,0,-1): (a[0], A[i])=Exchange (a[0], A[i]);Length=Length- 1;Maxheapfy (A,0, length);    returnA;A=[5,0,1,3,6,2,4,9, A, One, -, -,7,8, +, -, -, -, -,Ten];A=Heapsort (a);Print(a);

The idea of a heap is to understand the concept of the largest (small) heap: For a binary tree, the parent node is always small (large) on the child node, i.e.
A[parent (i)] >= a[i] ... ①

The latter makes it easy to say nothing about redundancy, only the maximum heap.

So the first goal of the heap is to establish a maximum heap that satisfies the condition, and to establish the maximum heap, it is necessary to have the maximum heap criterion, namely the ① type. After the maximum heap is established, the root node is found, saved, and rejected, and the remaining sequence continues to be the largest heap, repeating the process to complete the sorting.

Time Complexity O (Nlog (n))

Quick sort:

Attention is also the original sort!!!

defPartition (A, p, r): X=A[R];I=P- 1;     forJinch Range(P, R):ifA[J]<=X:i=I+ 1;(A[i], a[j])=(A[j], a[i]);(A[i+ 1], A[r])=(A[r], a[i+ 1]);    returnI+ 1;defQuickSort (A, P, R):ifP<R:q=Partition (A, p, R);QuickSort (A, p, q- 1);QuickSort (A, q+ 1, R);    returnA;A=[5,0,1,3,6,2,4,9, A, One, -, -,7,8, +, -, -, -, -,Ten];A=QuickSort (A,0,Len(a)- 1);Print(a);

The idea of a fast line is to divide the sequence into three parts a[0,i-1],a[i],a[i+1,n] and satisfy the condition a[0 that all elements in i-1] are less than or equal to a[i],a[i+1,n] and all the elements are greater than or equal to a[i]. The same can be achieved using recursive methods. If you don't understand it, you can refer to merge sort.
Time Complexity O (Nlog (n))

Python implementation method and principle of some sort 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.