The algorithm's classical sorting algorithm small induction

Source: Internet
Author: User
Tags array length

Objective

Data structures and algorithms are the basis for writing code. Basic skills are important, so-called foundation depth determines the height of growth. I have never eaten a good meal before, and I will come back to eat it someday. This time the project is not busy, come back to eat, decided to spend a period of time to smooth out the basic knowledge of data structures and algorithms.


Body

This blog briefly summarizes seven algorithms: Bubble sort, select sort, insert sort, hill sort, quick sort, merge sort and heap sort. All the descriptions in this article are based on their own understanding of the hand, in order to facilitate reading , the sample code can implement the algorithm, but not guaranteed to be optimal. If the description is wrong, please correct me.

All right, let's get started.

1. Bubble sort

Starting from one end of an array, 22 compares the current maximum value to the sorting method on the other end of the array. Measured, the speed is the slowest in these algorithms.

Code:

/** * Bubble sort (from small to large) *  * @param array * @return */private static void Bubblesequence (int[] array) {if (null! = array) {Lon G ts = System.currenttimemillis (); int length = array.length;for (int i = 0; i < length; i++) {for (int j = 0; J < le Ngth-1-I; J + +) {if (Array[j] > array[j + 1]) Exchange (Array, J, j + 1);}} Long te = System.currenttimemillis (); System.out.println ("bubble Sort time cost  (ms):" + (Te-ts));}}
2. Select Sort
Selects the element from one end of the array and then compares it to all other elements, then swaps the maximum value to the target position, in turnthe Sorting Method。

Code:

/** * Select sort (from small to large) *  * @param array * @return */private static void Selectsequence (int[] array) {if (null! = array) {Lon G ts = System.currenttimemillis (); int length = array.length;for (int i = 0; i < length; i++) {for (int j = i + 1; J < ; Length J + +) {if (Array[j] < Array[i]) Exchange (array, J, i);}} Long te = System.currenttimemillis (); System.out.println ("Select Sort time cost  (ms):" + (Te-ts));}}

3. Insert Sort

It is very efficient for partial ordered sequences to insert unordered sequence elements sequentially into ordered sequences. In the case of a completely unordered sequence, the initial ordered sequence length is 1.

Code:

/** * Insert sort by small to large *  * @param array * @return */private static void Insertsequence (int[] array) {Long ts = system.current Timemillis (); if (null! = array) {int length = Array.length;int temp = 0;//begins the insertion sort, and the first bit in the first i-1 bit in the position for (int i = 1; I < le Ngth; i++) {if (Array[i] > Array[i-1]) {//is larger than the previous value continue;} for (int j = 0; J < I-1; J + +) {//Pre-I-bits contrast if (Array[i] < array[j]) {temp = array[i];for (int k = i; k > J; k--) {Array[k] = array[k-1];//The element after the insertion position}array[j] = temp;//insert value break;}} Long te = System.currenttimemillis (); System.out.println ("Insert Sort time cost  (ms):" + (Te-ts));}}

4. Hill sort

In comparison, the first three types are relatively basic sorting methods, easy to understand. Starting from here, it's going to cost a little brains. Hill sort uses the basic sorting method of the insertion sort, its basic idea is: the array in accordance with a certain number of steps into sub-arrays , (popular for example, like let a row of people count, circulating 1, 2, 3, after the report after the call 1 for a group, shouting 2 for a group, shouting 3 for a group of artificial , the team was divided into three groups. The sub-array is then inserted in order to make it orderly. Then narrow the step, continue grouping, sort. Wait until the step is 1 o'clock and the sorting is complete. the efficiency of the measured hill sequencing is very high, ranging from more than 10 to dozens of times times faster than the previous three algorithms.

Code:

/** * Hill Sort *  * @param array * @return */private static void Shellsequence (int[] array) {if (null! = array) {Long TS = System.currenttimemillis (); int length = Array.length;int steplength = 1;//Step//Calculate initial step while (Steplength < LENGTH/3) { Steplength = steplength * 3 + 1;} while (steplength >= 1) {//Make an array of interval H into ordered for (int i = 0; i < steplength; i++)//Direct Insert sort {for (int j = i + steplength; J < length; J + = Steplength) if (Array[j] < array[j-steplength]) {int temp = Array[j];int k = j-steplength;while (k >= 0 & ;& Array[k] > Temp) {array[k + steplength] = array[k];k-= steplength;} Array[k + steplength] = temp;}} Steplength/= 3;//step shortening}long te = System.currenttimemillis (); System.out.println ("Hill Sort time cost  (ms):" + (Te-ts));}}

5. Merge sort

Merge Sort Dependency merge operation, the process of merging two sorted sequences into a sequence, The procedure is to split an array into two sub-arrays, and then split the sub-array ... Until the last subarray has a length of 1, then the sub-arrays are merged sequentially, 22 merged, and 22 merged until the original array length is restored, sorting is complete. There is a vivid motion diagram:


Code Recursive implementation:

/** * Merge Sort * * First split the array into sub-sequences, recursively, until the length of all sub-sequences is 1, then the 22 sub-sequences are merged and sorted, and the sorting is completed. * * @param array * To sort arrays * @param result * As an auxiliary array of nudge space * @return */private static void Mergesequenc  E (int[] array, int result[], int start, int end) {//Refer to Wikipedia's motion diagram, detach and close, recursively execute if (start >= end) return;if (null! = array) {int Length = end-start;int middle = (length >> 1) + start;int Start1 = start, End1 = Middle;int Start2 = middle + 1, End2 = end;mergesequence (array, result, Start1, End1), mergesequence (array, result, Start2, end2); int k = Start;while (star T1 <= end1 && start2 <= end2)//Compare values, merge sort result[k++] = Array[start1] < Array[start2]? array[start1++]: Array[start2++];while (start1 <= end1)//merge 1 tail result[k++] = array[start1++];while (start2 <= End 2)//merge 2 tail result[k++] = array[start2++];for (k = start; k <= end; k++)//The merged value is assigned back to the original array array[k] = Result[k];}}
6. Quick Sort

The process of quick sorting is, 1. Select an element as the base value, place the element that is larger than the base value aside, and the element that is less than the base value on the other side, forming the left and right two sub-sequences. The subsequence then continues to do this until the subsequence length is 1 and the sorting is complete.

Code:

/** * Quick Sort * According to a datum value, the array is divided into two sub-sequences greater than and less than this value, and then the recursive subsequence continues to be sorted by this method until the final subsequence length is 1 o'clock, and the sort is completed. * Small-scale experiments measured, sequencing efficiency is not stable, time is fast and slow, and specific arrays. * @param array to sort arrays * @param start * @param end */private static void Quicksequence (int[] array,int start, int end) {if ( Start >= end) Return;int mid = array[end];//The last element as the base value int left = start and right = end-1;//set: The sequence on the ieft is less than the reference value, and the sequence on the right is greater than the base value//from around two Searches for elements that are less than and greater than the base value in the middle of the edge, swapping elements that are not eligible on either side (left < right) {while (Array[left] < mid && left < right) left++ while (Array[right] >= mid && left < right) Right--;exchange (Array,left, right);} After the search is complete, if the left element is also greater than the base value, it is exchanged with the base value, which occurs when the base value is exactly selected as the minimum value in the sequence if (Array[left] >= Array[end]) Exchange (Array,left, end) ; elseleft++;//recursive operation left sequence quicksequence (Array,start, left-1);//recursive operation right sequence quicksequence (Array,left + 1, end);}

7. Heap Sequencing

Heap Sorting is a sort of data structure using heap. The heap is a fully binary tree that satisfies the condition that all parent nodes are not more than or less than the child nodes. If the parent node value is greater than the child node, it is called the Big Top heap, and vice versa, called the small top heap. the heap sort ordering process is: 1. First, construct a pile of arrays of structures, see:
The root node exists at ordinal 0, and the parent node of the I node is labeled (i-1)/2 . The index of the left and right sub-nodes of the I node is 2*i+1 and the 2*i+2 . 2. After the basic structure has been constructed, the adjustment is made to conform the data to the characteristics of the heap . When you adjust, you should start with the last subtree structure and adjust it up and down. 3. After the heap is paged out, start sorting. the process of sorting is to data at the top of the heap (maximum or minimum data)In turn, the exchange to the last data is fixed (because the order has been adjusted, as ordered), and then the heap is adjusted, continuing to exchange the most value to the end of the unordered sequence. The process of adjustment is the process of moving the maximum value of the current stage forward. When you move to the back of an ordered sequence that fills the entire array, the sorting is complete. Therefore, the essence of heap ordering is actually the choice of sorting, but it is more efficient than the direct selection of sorting to reduce a lot of repetitive comparison process. So, one of the most important operations of heap sequencing is to adjust the heap structure.
The following shows an example {3,4,6,7,2,1,8,5} 1. Constructing the heap structure
2. After adjustment, construct a large top pile
3. Construct a sort of data structure after starting according to the third step above, at this time, the largest data in the array is already on top of the heap, to drain the data from small to large, in order to move the largest number to the last. The red box is the item to be exchanged, and the green box is the ordered part that is fixed. each adjustment, the unordered part is constructed as a large top heap structure. For each interchange, the maximum value is swapped to the end of the unordered sequence.

If you follow the fixed code logic, you will continue to adjust the two rounds to the previous step, and then the sorting is complete. Code:
Package com.test;/** * Heap Sorting * * @author Administrator * */public class Heapsequence {/** * finishing heap (organized as a large top heap) * * @param array  */public void Createheap (int[] array) {if (null! = array) {int startpst = getfatherposition (array.length-1); for (int i = Startpst; I >= 0; i--) {Sortnode (array, I, Array.Length);}}} /** * Sort * * @param array */public void SortHeap (int[] array) {if (null! = array) {for (int i = array.length-1; i > 0; i--) {Exchange (array, 0, I); Sortnode (array, 0, i);}}} public void sort (int[] array) {createheap (array); sortHeap (array);}  /** * Defragment the heap structure of a single node * @param array * Target array * @param nodeposition * node location */private void Sortnode (int[] Array, int nodeposition, int heapsize) {int leftchildpst = getleftchildposition (nodeposition); int rightchildpst = GetRigh Tchildposition (nodeposition); int largestposition = Nodeposition;if (Leftchildpst < heapsize && array[ Largestposition] < Array[leftchildpst]) {largestposition = Leftchildpst;} if (RightchildpsT < heapsize && array[largestposition] < Array[rightchildpst]) {largestposition = Rightchildpst;} Child node value changes, continue to defragment if (largestposition! = nodeposition) {Exchange (array, largestposition, nodeposition); Sortnode (array , Largestposition, heapsize);}} /** * Parent Node Location * * @param currpst * @return */public int getfatherposition (int currpst) {return (currPst-1)/2;} /** * Left child node position * * @param currpst * @return */public int getleftchildposition (int currpst) {return currpst * 2 + 1;} /** * Right child node position * * @param currpst * @return */public int getrightchildposition (int currpst) {return currpst * 2 + 2;} /** * Swap values for two positions in the array * * @param a * array * @param x * Position 1 * @param y position 2 */private static void Exchange (I Nt[] A, int x, int y) {int temp = 0;temp = a[x];a[x] = a[y];a[y] = temp;}}
Finally, random pairs of arrays of length 100,000test a single order , the speed at which the sample code runs on this computer:Resource code Download:Click to open linkHeap Sort Resource code:Click to open link

The algorithm's classical sorting algorithm small induction

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.