Summary of common sorting algorithms---java implementation

Source: Internet
Author: User

Summary of each sort, and time, spatial complexity analysis
One. Bubble sort:
/* Bubble sort: Sort algorithm idea: Make n-1, each trip, adjacent elements, 22 compare each other, if the previous element is smaller than the latter, it will be exchanged. (The final result is that the small backward (from large to small bubbling)) */class bublesort {public static void main (string[] args) {int[] arr = {1,4,6,3,7,4,9,8};bsort_1 ( ARR); for (int a:arr) {System.out.print (A + ".");}} /* Optimization of the algorithm: A Boolean variable can be set, the initial value is false, if an interchange occurs, it is changed to true, if its value does not change, still false, you can end prematurely.  *///from large to small bubble (outer control number, inner layer) public static void Bsort (int[] arr) {Boolean flag = false;for (int i=0;i<arr.length-1; i++) {flag = false;for (int j=0;j<arr.length-i-1; j + +) {if (arr[j]<arr[j+1]) {flag = True;swap (arr,j,j+1);}} if (!flag) break;}} Bubbles from small to large (if the previous number is larger than the latter, it is exchanged)//2 4 6 7 5 3 4//7 public static void Bsort_1 (int[] arr) {Boolean flag = false;for (int i=0;i& lt;arr.length-1; i++) {flag = false;for (int j=arr.length-1;j>i+1; j--) {if (Arr[j]<arr[j-1]) {flag = True;swap (arr, J,J-1);} if (!flag) break;}}} public static void Swap (int[] Arr,int i,int j) {int temp = Arr[i];arr[i] = arr[j];arr[j] = temp;}}

Two. Select sort
/* Simple selection sorting: The idea of the sorting algorithm: an array of n elements, a n-1, the number of the default current trip per trip is the smallest (large), and then the comparison in the trip. The comparison element should be from the number of times +1, find the largest, put it in the array is already a well-sequenced element (that is, the position of the current number of times, that is, the maximum value and the current number of the corresponding element to swap position). */class selectsort {public static void main (string[] args) {int[] arr = {1,4,6,3,7,4,9,8};ssort (arr); for (int a:arr) {Syst Em.out.print (A + ");}}  public static void Ssort (int[] arr) {for (int i=0;i<arr.length/* can be optimized here (one Less time): arr.lenth-1*/; i++) {int index = i;for (int J=i+1;j<arr.length; j + +) {if (Arr[index]>=arr[j]) {index = j;}} if (index!=i) {swap (arr,index,i);}}} public static void Swap (int[] arr,int index,int i) {int temp = Arr[index];arr[index] = arr[i];arr[i] = temp;}}
Three. Quick Sort
Class QuickSort {public static void main (string[] args) {int[] arr = {50,10,90,30,70,40,80,60,20}; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"); quick (arr); System.out.println ("--------sort completed--------"); System.out.println (java.util.Arrays.toString (arr));} /* Quick row. Thought: For the subsequence of the array from the Start--end index range to be processed, so that it satisfies all the less than the cutoff value on the left, all the greater than the cutoff value on the right side (starting at both ends of the edge), because the observed each time is in the left sequence or right sequence operation, then you can use a recursive method * * private static void Quick (int[] arr) {subsort (arr,0,arr.length-1);} private static void Subsort (int[] arr,int Start,int end) {//interval exists, indicating need to sort if (start<end) {//With first element as the cutoff value int base = arr[ Start];//i search from the left, search for an index greater than the cutoff value int i = Start;//j search from the right, search for an index less than the cutoff value int j = End+1;while (true) {//--i is the first operation in use (so J starts from End+1, And I need to start from start, because start is the cardinality)//Find the index of the element greater than the cutoff value, or I have reached end while (I < end && Arr[++i] <= base);//Find the index of the element less than the cutoff value, Or J has arrived at start while (J>start && arr[--j] >= base); if (i<j) {//Description interval has not been traversed, swap (ARR,I,J) The two numbers found this time;} else{//indicates that the end interval is done with a System.out.println (java.util.Arrays.toString (ARR)); break;}} The base base and sequence intermediate values are exchanged for swap (arr, start, j);//recursive fast-sequence left subsequence subsort (arr,start,j-1);//recursive fast-sequence right-order subsort (Arr,j+1,end);}} private static void Swap (int[] Arr,int i,int j) {/* Do not use a third-party variable to complete the two-number exchange principle: A = 5, b = 3a = a + b;//a = 3 + 5;b = A;//b = 8 -3 = 5;a = A-B; A = 8-5 = 3*/arr[i] = Arr[i] + arr[j];arr[j] = Arr[i]-arr[j];arr[i] = Arr[i]-arr[j];}}

Four. Insert Sort
Class  insertsort{public static void Main (string[] args) {int[] arr = {50,10,90,30,70,40,80,60,20}; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"); Insertsort (arr); System.out.println ("--------sort completed--------"); System.out.println (java.util.Arrays.toString (arr));} public static Voidinsertsort (int[] arr) {//insert sort directly. Think: You want to insert the current I element into an array where the first n-i is already sorted (N-1 inserts are required, the element does not need to be inserted) for (int i = 1;i<arr.length; i++) {//record the current value, ensuring that the array does not lose int during the move back temp = arr[i];//Because the number of previous i-1 is already a series of rows, I-1 max, if I is larger than i-1, then it is ordered that no insert operation is required if (Arr[i]<arr[i-1]) {int J = i-1;// Move the whole back one pane while (j>=0 && arr[j]>temp) {//loop judgment and backward, if the current element is greater than temp, the position is not temp at the insertion position, then move backward. Until an element is found that is less than temp, the next one in that position is exactly where it was inserted arr[j+1] = arr[j];j--;} Find location insert arr[j+1] = temp;} System.out.println (java.util.Arrays.toString (arr));}}}

Five. Binary insert
Class Binarysearchinsertsort {public static void main (string[] args) {int[] arr = {50,10,90,30,30,70,40,80,60,20}; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"); Binarysearchinsertsort (arr); System.out.println ("--------sort completed--------"); System.out.println (java.util.Arrays.toString (arr));} /* Binary insert sort. Thought: is actually an improvement on the direct insertion sort. will be looking for the current element to be inserted into the ordinal sequence, using the binary lookup method instead of */public static void Binarysearchinsertsort (int[] arr) {for (int i = 1; i<arr.length; i++) {//Also first remember the value of the current position. int temp = arr[i];//also need to determine the insertion position if the current value is less than the maximum value in the sequence, otherwise you do not need to insert if (Arr[i]<arr[i-1]) {//Start binary lookup int low = 0;int High = i-1;//idea: here For the mid-subscript value and the temp comparison, if you encounter an equality situation, you can directly set the low value at this point to mid. Then jump out of the loop. This optimizes the number of comparisons while (low <= high) {int mid = (low + high)/2;if ( Temp>arr[mid]) {//Limit index in larger than mid half find low = mid + 1;} else if (Temp<arr[mid]) {//Limit index in less than mid that half find high = mid-1;} else {low = Mid;break;}} Determines the position of the current value (low position), and then moves the array for (int j = i; j>low; j--) {arr[j] = arr[j-1];} Inserts the current value into the low position arr[low] = temp;} System.out.println (java.util.Arrays.tostring (arr));}}} 

Six. Heap sequencing
Heap sort: mainly divided into heap and, sort adjustment heap class Heapsort{public static void Main (string[] args) {int[] arr = {9,79,46,30,58,49,22,44,12,23,45} ; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"), Heap (arr);} public static void Heap (int[] arr) {//Loop build heap (after each build, the heap needs to be adjusted after the sort is finished.) ) for (int i = 0;i<arr.length; i++) {//Jian Yu buildmaxheap (arr,arr.length-i-1);//Swap heap top and last element swap (arr,0,arr.length-1-i); System.out.println (java.util.Arrays.toString (arr));}} Jandagen private static void Buildmaxheap (int[] arr,int lastIndex) {//starting from the parent node of the LastIndex node for (int i= (lastIndex-1)/2;i>= 0; i--) {//k Saves the node that is currently being judged int k = i;//If the child nodes of the current K node exist (looping to determine the size of the two child nodes and the current node value) (This is why you should use the while loop, because the following heap order may be chaotic after the current heap exchange and need to be down again) while (K*2+1<=lastindex) {The index of the left child node of the//k node int biggerindex = 2*k+1;if ((biggerindex+1) <=lastindex) {The Right child node of the//k node exists if ( Arr[biggerindex]<arr[biggerindex+1]) {//Right child nodes with larger values (using Biggerindex to record larger nodes) biggerindex++;}} If the value of the K-node is less than the value of its larger child node if (Arr[k]<arr[biggerindex]) {//swaps them swap (arr,k,biggerindex);//assigns the value of Biggerindex to the K-node, And start the next whil.E-loop (determine the child node under the Sub-node has a larger than the current maximum node value)//new guarantee K node value is greater than the value of its left and right child nodes k = Biggerindex; } Else{break;}}} private static void Swap (int[] Arr,int i,int j) {int temp = Arr[i];arr[i] = arr[j];arr[j] = temp;}}

Seven. Shell sorting
Class Shellsort {public static void main (string[] args) {int[] arr = {50,10,90,30,70,40,80,60,20,110,800,200,100,12}; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"); Shellsort (arr); System.out.println ("--------sort completed--------"); System.out.println (java.util.Arrays.toString (arr));} public static void Shellsort (int[] arr) {/*shell sort. Idea: The shell is a close improvement of the direct insertion sort. Just insert the sort directly in increments of 1 for each insertion. Change to H (shell value), and then decrement the H by a certain law, making the insertion sort until h<0. Why do you do this? Because the insertion sort has a feature, if the sequence is basically ordered (small elements in front, large elements in the back, medium elements in the middle), then we only need to move the sequence very rarely. General values for h: h = length, H = H/3 + 1;*///determines the shell value int h = 1; while (H <= arr.length/3) {h = h*3 + 1;} The shell value >0, proceed with the insertion sort while (h>0) {//A trip with an H-spaced insertion sort complete. System.out.println ("Value of current H" + h); for (int i=h;i<arr.length; i++) {//Insert sort with H for spacing//Remember the value currently being inserted int temp = arr[i];// If the current value is larger than the maximum value in the sequence (i-1), the position is correct, no insertion is required, otherwise insert if (Temp<arr[i-h]) {int J = i-h;//moves back with H, if ARR[J] is greater than the temp description, the insertion position is not found, The position moves back while (j>=0 && arr[j]>temp) {Arr[j+h] = Arr[j];j = j-h;} ARR[J+H] = temp;} SyStem.out.println (java.util.Arrays.toString (arr));} h = (h-1)/3;}}}

Eight. Merge sort
Class Mergesort{public static void Main (string[] args) {int[] arr = {50,10,90,30,70,40,80,60,20}; System.out.println (java.util.Arrays.toString (arr)); System.out.println ("--------sort begins--------"); MergeSort (arr); System.out.println ("--------sort completed--------"); System.out.println (java.util.Arrays.toString (arr));} public static void MergeSort (int[] arr) {/* merge sort. Idea: The algorithm has a kind of divide and conquer thinking is to turn large problems into several small problems, then the solution of each small problem together, is the solution of big problem, merge sort is to adopt this idea. Sorting a series of data, and then splitting it down until one element of each group, then the direct row. Then the grouping of the order is sorted and merged together. So two steps, split, merge. About decomposition we can do it by recursion. */sort (arr,0,arr.length-1);} Merges the index from the left to the right range of the array elements to sort. (First step decomposition) private static void sort (int[] arr,int left,int right) {//existence interval, can be sorted if (left<right) {///Find intermediate index, bounded by intermediate index, explode int Center = (left+right)/2;//recursively sorts the left part of the array sort (arr,left,center),//recursively sorts the right part of the array sort (arr,center+1,right);//Start merging (when left= Right start) merge (Arr,left,center,right);}} Merges the left-to-center and center+1-to-right arrays (the second merge)//merges two arrays, merges the first two arrays in order, and remains orderly after merging. private static void merge (int[] Arr,int left,int center,int right) {//need to create an auxiliary array of equal size (intermediate array) to hold the array after merging int[]Temparr = new Int[arr.length];int mid = center + 1;//third Record Intermediate array (secondary array) index int third = left;//The starting subscript of the array of record tuples (used to last copy the return array with) int tem p = left;//in two arrays there are also values that are not traversed while (Left<=center && mid<=right) {//from two arrays are taken from a small drop into the middle array if (arr[left]<arr[ Mid]) {temparr[third++] = arr[left++];} else{temparr[third++] = arr[mid++];}} The above two arrays may have an array and the values are not traversed. Next, put the possible remaining array into the middle array while (Left<=center) {temparr[third++] = arr[left++];} while (Mid<=right) {temparr[third++] = arr[mid++];} The above has merged two arrays into the same array. Copies the contents of the intermediate array to the original array (the contents of the original Left--right range are copied back to the tuple), forming a larger ordered set while (Temp<=right) {arr[temp] = temparr[temp++];} At this point a small interval is merged. System.out.println (java.util.Arrays.toString (arr));} private static void Swap (int[] arr, int i, int j) {/* Do not use third-party variables, exchange values of two variables a = a ^ B;b = a ^ b;//B = (a ^ b) ^ b = A;a = a ^ b; A = a ^ (a ^ b) = B;*/arr[i] = arr[i] ^ arr[j];arr[j] = Arr[i] ^ Arr[j];arr[i] = Arr[i] ^ arr[j];}}

Nine. The space-time complexity and stability analysis of common algorithms.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Summary of common sorting algorithms---java implementation

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.