Various sorting algorithms Python and Java implementations (ii)

Source: Internet
Author: User
Tags array sort

The first blog has implemented three most basic and simple sorting algorithms, and this article will evolve slightly based on these three algorithms.

1. Quick-Line

light from the name to know the speed is certainly not bad, the previous story of the bubble sort, how to see is not a good sort of algorithm, filled with too much unnecessary exchange action, time complexity is very stable O (n^2), but it is not justified for sorting algorithms. The quick row is the improved version of bubble sort, the idea is divide and conquer, a sequence randomly according to a value into two sub-series, the value of sub-sequence A is all larger than the value, the other sub-sequence B's value is all smaller than the value, which sounds like a two-fork sort tree. Then the sequence is performed as above, and it is obvious that the simplest implementation of the fast line is recursive.

Look at the Java implementation of the quick row:

/** * Fast sequencing, fastest O (nlogn) worst O (n^2) *  * @param low * @param high * @param array */public static void QuickSort (int low, int High, int[] array) {if (low >= high) {return;} int i = low;int j = high;//The middle axis selected here is the intermediate value of the current I and J int m = (i + j)/2;int temp = array[m];array[m] = Array[high];array[high] = temp;//middle Axis int PivotKey = Array[high];while (i < J) {while (I < J && Array[i] <= pivotkey) {i++;} ARRAY[J] = Array[i];while (i < J && Array[j] >= pivotkey) {j--;} Array[i] = array[j];} At this point I and J are equal, replace the value of the current I array[i] = pivotkey;//to the left subset to do a fast row quicksort (low, i-1, array);//Make a quick row quicksort (i + 1, high, array) on the right subset;}

and then look at the python implementation:

def quickSort (Low,high,array): If low > High:returni, j = LOW,HIGHM = (i+j)/2temp = array[m]array[m] = array[high]array[ High] = Temppivotkey = Array[high]while I < J:while i < J and Array[i] < pivotkey:i+=1array[j] = Array[i]while I < J and Array[j] >= pivotkey:j-=1array[i] = array[j]array[i] = Pivotkeyquicksort (Low,i-1,array) QuickSort (I+1,high , array)
Without a variety of curly braces it looks pleasing to the eye. 2. Various direct insert sorted versions. In fact, the main problem of direct insertion is to find the position with the insertion value, since the subset is already ordered, then it is advisable to use a faster method, two-point lookup to complete the index search. Look directly at the code:
/** * Binary Find Insertion sort of index * @param array */public static void Insertsortbinary (int[] array) {for (int i=1;i<array.length;i++) {int temp = Array[i];int index = binarysearch (0, I, array, array[i]); for (int j=i;j>index;j--) {Array[j] = array[j-1];} Array[index] = temp;}} /** * Two-point search for micro-revision * @param start * @param end * @param array */public static int binarysearch (int start,int end,int[] Array,in T value) {while (start <= end) {int mid = (start + end)/2;if (array[mid] = = value) {return mid;} else if (Array[mid] < value) {start = mid + 1;} Else{end = Mid-1;}} return start;}
Python implementations:
def insertsortbinary (array): For I in Xrange (1,len (array)): index = Binaryserach (Array,array[i]) for J in Range (Index,i) [: : -1]:array[j] = Array[j-1]array[i],array[index] = array[index],array[i]def Binaryserach (array,value): Low,high = 0,len (array) -1while low <= High:mid = (low + high)/2if value = = Array[mid]:return Midelif value < Array[mid]: High = mid -1else:low = mid + 1return Low
The hill sort is also an insertion sort, except that it keeps the whole sequence in order, which speeds up the sorting speed, and the Java implementation:
/** * Hill Sort, step g direct insertion Sort if part of the order of the speed is significantly increased, so consider using the Division method, first let the subset order, and then insert here there is a concept of step, * that is, the subset of this step in order to gradually expand the step size, so that the overall order */public static void Shellsort (int[] array) {int[] Gs = {5,4,3,2,1};for (int i=0;i<gs.length;i++) {shellinsert (array, gs[i]);}} /** * Hill Insert, just more step g *  * @param array * @param g */public static void Shellinsert (int[] array, int g) {int temp,j;for ( int i = g; i < Array.Length; i + = g) {temp = Array[i];for (j = i-g; J >= 0; j-=g) {if (temp < array[j]) {array[j + G] = array[j];} else {break; }}ARRAY[J+G] = temp;}}
Python implementations:
def shellinsert (array,g): For I in range (G,len (array), g): If array[i] < array[i-g]:temp = array[i]for j in range (0,I,G) [: : -1]:if Temp < Array[j]:array[j+g] = array[j]else:j+=gbreakarray[j] = tempdef shellsort (array): Gap = [5,4,3,2,1]for x i N Range (1,6) [:: -1]:shellinsert (ARRAY,X)



3. Based on the simple selection of the sorting, can derive more complex heap sorting, review of the simple sort is to select the first I or I small value of the process, in fact, the characteristics of the heap is very good to meet this feature, first see what the heap is?heaps have the largest heap, the smallest heap, just from small to large, from big to small differences,first the heap is a data structure, is a completely binary tree and satisfies the nature: all non-leaf node values are not greater than or are not less than the value of their left and right child nodes (looked at and two fork search tree definition somewhat similar), as follows is a heap example:
for the characteristics of the heap, the speed of adding an element like an ordered heap is fast, because finding the position to be inserted is much faster, since the heap is a data structure, then what structure will be used to store it, usually like this more complex structure is a linked list implementation, in fact, using arrays to implement the heap is very convenient, The process of heap sequencing is actually the process of building a heap, here to build a maximum heap as an example, since the heap is a complete binary tree, it is possible to start from the heap, from left to right by the array sort such as the above tree can be represented as {9,8,5,3,1,2}, assuming that a tree in a non-leaf node as subscript i, You can have key[i]>=key[2i+1] && key[i]>=key[2i+2] Here I start from 0. The process of creating the heap is actually the process of constantly adjusting the heap, first look at the idea of the heap adjustment:
too lazy to draw, directly using other people to draw a good diagram, I and 2i+1,2i+2 three elements of the largest value and I exchange, and then in turn the value of the exchange as I to deal with, here can use recursive form or non-recursive (quasi-end) condition until I is a leaf node. Look at the Java implementation:
/** * Adjusts a sub-heap, starting from top to bottom from the I node. Adjust maximum value to heap top * * @param array * @param i */public static void Adjustheap (int[] array, int i, int len) {int maxindex = i;//I For leaves and nodes if ((2 * i + 1) >= len) {return;} There must be left child else {//left child greater than father if (Array[i] < array[2 * i + 1]) {Maxindex = 2 * i + 1;//have right child}if ((2 * i + 2) < Len) {Syst Em.out.println ("with Right"), if (Array[maxindex] < array[2 * i + 2]) {Maxindex = 2 * i + 2;}}} Swap if (maxindex! = i) {int temp = Array[i];array[i] = Array[maxindex];array[maxindex] = temp;//recursive adjustment adjustheap (array, MA Xindex, Len);}} /** * Heap building process, is the process of adjustment from the bottom image, the first to start adjusting is the last non-leaf node * * @param array */public static void Createheap (int[] array) {if (Array.leng Th <= 1) {return;} Starting from the last non-leaf node adjust for (int i = ARRAY.LENGTH/2-1; I >= 0; i--) {adjustheap (array, I, Array.Length);}} public static void Heapsort (int array[]) {createheap (array), for (int i = array.length-1; I >= 0; i--) {int temp = arr Ay[0];array[0] = Array[i];array[i] = temp;adjustheap (array, 0, i);}}

The heap is adjusted for the process execution time and the heap is highly h related, so the time is O (Logn), and the heap building process is an n-based loop, so the time to build the entire heap is O (Nlogn). python implementations:
def heapsort (array): Buildheap (array) for x in Xrange (0,len (array)): Array[0],array[len (array)-x-1] = Array[len (array)- X-1],array[0]adjustheap (Array,len (array)-x-1,0) #from last no leave nodedef buildheap (array): x = Len (array)/2-1while x& Gt;=0:adjustheap (Array,len (array)-x,x) X-=1#from top to Downdef adjustheap (array,size,root): Maxindex = rootif (2*root + 1) >= size:returnif array[2*root+1] > array[maxindex]:maxindex = 2*root + 1if (2*root+2) < Size:if array[2*root+2 ] > Array[maxindex]:maxindex = 2*root+2if maxindex!=root:array[maxindex],array[root] = Array[root],array[maxIndex] Adjustheap (Array,size,maxindex)


4. Merge sortMerge sort is a typical divide-and-conquer thought to think of a large set as two ordered collections, when merging two subsets, form a large ordered set, and finally divide to two subsets of each element, see the code:
 /** * Merge Sort, recursive call * @param array * @param start * @param end */public static void MergeSort (int[] A        Rray,int Start,int End) {if (start >= end) {return;        } int mid = (start + end)/2;        MergeSort (Array, start, mid);        MergeSort (Array,mid + 1,end);    Merge (Array,start,end,mid); }/** * Merge method, merge two ordered subsets * @param array * @param start * @param end */public static void merge    (int[] Array,int start,int end,int mid)        {int[] temp = new Int[end-start + 1];        int i = start;        Int J = Mid +1;        int k = 0; while (I <= mid && j<=end) {if (Array[i] < array[j]) {temp[k            + +] = array[i++];            } else {temp[k++] = array[j++];        }}//Copy the remaining value to temp while (I<=mid) {temp[k++] = array[i++]; } while (J<=end) {temp[k++] = array[j++];    } system.arraycopy (Temp,0,array,start,end-start + 1); }
Python implementations:
def mergesort (Array,low,high): If Low>=high:returnmid = (Low+high)/2mergesort (array,low,mid) MergeSort (array,mid+ 1,high) Merge (Array,low,high,mid) #merge the listdef merge (array,low,high,mid): Temp_array = []I,J = Low,mid+1while i< =mid and J<=high:if array[i]<array[j]:temp_array.append (Array[i]) i+=1else:temp_array.append (Array[j]) j+= 1while i<=mid:temp_array.append (Array[i]) i+=1while j<=high:temp_array.append (array[j]) J+=1for x in xrange (0, Len (Temp_array)): array[low] = temp_array[x]low+=1

Recently this time on a business trip, basically no time to write a blog, but still squeeze out a little time to finish it, or some things did not complete, the heart is always uncomfortable.

Various sorting algorithms Python and Java implementations (ii)

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.