Java Sorting algorithm

Source: Internet
Author: User

Java sorting algorithm 1) Category: 1) Insert sort (direct insert sort, hill sort) 2) Swap sort (bubble sort, quick Sort) 3) Select sort (Direct select sort, heap sort) 4) Merge sort 5) Allocation sort (box sort, cardinal sort) required auxiliary space max: merge sort Minimum required secondary space: Heap sorting speed fastest: Fast sort instability: quick sort, hill sort, heap sort. 1) Select the Sort algorithm 1. The size of the data; 2. The type of data; 3. The order in which the data is available in general, you should choose to insert a sort or bubble sort directly when the data size is small. Any sorting algorithm in the data volume hours is basically not out of the gap. Consider the types of data, such as if all are positive integers, then consider using bucket ordering to be optimal. Considering that the data is already in order, the queue is an unstable sort (which can be improved, of course), and for most rows of data, a quick run will waste a lot of unnecessary steps. The amount of data is very small, and since it has been basically sequenced, bubbling is the best choice. We say that the quick row, is the large number of random data, the effect of the fast row is ideal. Rather than all the circumstances. 3) Summary:--According to the average time performance to divide: 1 The time complexity is O (Nlogn) methods are: fast sorting, heap sorting and merge sort, in which fast sorting is the best; 2) time complexity is O (N2): Direct insert sort, bubble sort and simple select sort, with direct insert as best, This is especially true for the sequence of records in which the keywords are approximately ordered; 3) The sorting method of the time complexity is O (n) only, the Cardinal sort. When the sequence of sequential records is ordered by keyword, the time complexity of O (n) can be achieved by direct insertion of sort and bubble sort, and for fast sorting, this is the worst case, when the time performance is degenerate to O (N2), so it should be avoided as much as possible. The time performance of simple selection sorting, heap sorting, and merge sorting does not change with the distribution of the keywords in the record sequence. --in terms of average spatial performance (refers to the amount of secondary space required in the sorting process): 1) All simple sorting methods (including: direct insertion, foaming and simple selection) and heap sorting of the spatial complexity of O (1); 2) A quick sort of O (Logn), the necessary auxiliary space for the stack; 3) The most necessary auxiliary space for merging and sorting is the space complexity of O (n); 4) The chain base order must be attached to the queue end-to-end pointer, the space complexity is O (rd). --the stability of the sequencing method: 1) The stable sorting method refers to the relative position of the two key words in the sequence, before and after ordering, for the records that are equal to each other. 2) A stable sorting method must be used when ordering the LSD method for the sequence of records of multiple keywords. 3) for the unstable sorting method, as long as you can cite an example to illustrate. 4) Quick RowOrder, the hill sort and the heap sort are unstable sorting methods. 4) Insert sort: include direct insert sort, hill insert sort. Direct Insert Sort: Inserts a record into an ordered table that is already sorted. 1, the No. 0 position of the sorted array does not place data. 2, start processing from sorted second data: If the data is smaller than the data in front of it, it indicates that the data is moving forward. First put the data back into the No. 0 position of the sorted as Sentinel. Then move the data in front of that data back. Then go ahead and search for the insertion position. After locating the insertion position, the No. 0 position data is inserted in the corresponding location. O (n*n), the time complexity is increased to O (n) when the pending sequence of records is positive. Hill sort (Narrow incremental sort diminishing increment sort): First, the entire backlog of records is divided into several sub-sequences to directly insert the sort, and then once the records in the whole sequence are basically ordered, then the whole record is sorted by a direct insertion.

Insert Sort Java code: public class Insertionsort {//Insert sort: Direct Insert sort, hill sort public void Straightinsertionsort (double [] sorted) {int S Ortedlen= sorted.length; for (int j=2;j<sortedlen;j++) { if (sorted[j]<sorted[j-1]) { sorted[0]= sorted[j];//first save the back of the sorted [The one in front of the j]=sorted[j-1];//is shifted.] int insertpos=0; for (int k=j-2;k>=0;k–) {if (sorted[k]>sorted[0]) {sorted[k+1]=sorted[k];} else{insertpos=k+1; break;}} SORTED[INSERTPOS]=SORTED[0]; }}} public void Shellinertionsort (double [] sorted, int inc.) {int sortedlen= sorted.length; for (int j=inc+1;j<sortedl en;j++) { if (Sorted[j]<sorted[j-inc]) { sorted[0]= sorted[j];//first save the following

int insertpos=j; for (int k=j-inc;k>=0;k-=inc) {if (sorted[k]>sorted[0]) {sorted[k+inc]=sorted[k];//data structure There is no interpretation of this place in the textbook, Error: if ( k-inc<=0) {insertpos = k;}} else{insertpos=k+inc; break;}} SORTED[INSERTPOS]=SORTED[0]; }}} public void Shellinsertionsort (double [] sorted) {int[] incs={7,5,3,1}; int num= incs.length;

int inc=0; for (int j=0;j<num;j++) {inc= incs[j]; Shellinertionsort (sorted,inc);}} public static void Main (string[] args) {Random random= new random (6);

int arraysize= 21; Double [] sorted=new double[arraysize]; System.out.print ("Before Sort:"); for (int j=1;j<arraysize;j++) {sorted[j]= (int) (random.nextdouble () * 100); System.out.print ((int) sorted[j]+ "");} System.out.println ();

Insertionsort sorter=new Insertionsort (); Sorter.straightinsertionsort (sorted); Sorter.shellinsertionsort (sorted);

System.out.print ("After Sort:"); for (int j=1;j<sorted.length;j++) { system.out.print ((int) sorted[j]+ "");} System.out.println (); }} 5) Exchange sort: Includes bubble sort, quick sort. Bubble Sort method: This algorithm is a sort algorithm which is specially ordered for the data that has been partially sorted. This algorithm is the fastest sorting algorithm if only one or two of the data in your list is out of order. If the data in your list is randomly arranged, then this method becomes the slowest algorithm. Therefore, you must be cautious before using this algorithm. The core idea of this algorithm is to scan a list of two adjacent items that appear to be in a disorderly order. After you find these two items, swap the location of the project and continue scanning. Repeat the above operation until all items are sorted in order. Quick sort: the records to be sorted into separate two parts, some of which are smaller than the ones recorded by the other, can be sorted in order to achieve the order of the whole sequence. The practice is: using two pointers Low,high, the initial value is set to the head of the sequence, and the end of the sequence, set PivotKey as the first record, first from high start searching forward to the first record less than PivotKey and PivotKey location to Exchange, Then from low start to search backward the first record greater than PivotKey and the location of PivotKey at this time to exchange, repeat know Low=high so far. Interchange sort Java code: public class Exchangesort {public void Bubbleexchangesort (double [] sorted) {int sortedlen= sorted.length; fo R (int j=sortedlen;j>0;j–) {int end= J; for (int k=1;k<end-1;k++) { double tempb= sorted[k]; sorted[k]= sorted[k ]&LT;SORTED[K+1]?  sorted[k]:sorted[k+1]; if (Math.Abs (SORTED[K]-TEMPB) >10e-6) {SORTED[K+1]=TEMPB;}} }} public void QuickexchangesoRtbacktrack (double [] sorted, int low,int high) {if (Low

int arraysize=; double [] sorted=new double[arraysize]; System.out.print ("Before Sort:"); for (int j=1;j<arraysize;j++) { sorted[j]= (int) (random.nextdouble () * 100); System.out.print ((int) sorted[j]+ "");} System.out.println ();

Exchangesort sorter=new Exchangesort (); Sorter. Bubbleexchangesort (sorted); Sorter. Quickexchangesortbacktrack (sorted, 1, arraysize-1); System.out.print ("After Sort:"); for (int j=1;j<sorted.length;j++) { system.out.print ((int) sorted[j]+ "");} System.out.println (); }} 6) Select Sort: Divided into direct selection sort, heap sort directly Select the sort: I select I to array. The smallest value in the middle of the Length-1 is placed in the I position. Heap sort: First, the array is placed in the order of the hierarchical traversal of a complete binary tree. From the last non-terminal node to the front adjustment, until the root node is reached, this time all the non-terminal nodes outside the root nodes have been satisfied with the heap conditions, so need to adjust the root node so that the entire tree satisfies the heap conditions, and then start from the root node along its sons go down (the largest heap along the largest son walk, Minimum heap walking along the youngest son). In the main program, first from the last non-terminal node to adjust to the root is also adjusted to form a heap, and then put the root of the heap to the back (that is: each time the tree size will change, but Root is in the 1 position, to facilitate the calculation of the sons of index, so if you need to arrange in ascending order, You have to step up the heap of large tops. Because the root node is left behind one by one. In descending order to create a small top heap) The problem in the code: sometimes the 2nd and 3rd orders are incorrect (the reason why the code is wrong) Select sort Java code: public class Selectionsort {public void Straitselectionsort (double [] sorted) {int sortedlen= sorted.length; for (int j=1;j<sortedlen;j++) { int jmin= Getminindex (SORTED,J); Exchange (Sorted,j,jmin); }} public void Exchange (double [] sorted,int i,int j) {int sortedlen= sorted.length; if (I<sortedlen & &= "" j<sortedlen= "" i=0 && j>=0) {double temp= sorted[i]; sorted[i]=sorted[j]; sorted[j]=temp;}} public int Getminindex (double [] sorted, int i) {int sortedlen= sorted.length;

int minj=1; Double min= Double.max_value; for (int j=i;j<sortedlen;j++) {if (sorted[j]<min) {min= sorted[j]; minj= j;}} return Minj; }

public void Heapadjust (double [] sorted,int Start,int end) {if (start<end) {double temp= sorted[start];//This place j<end Unlike textbooks, J<=end will error: for (int j=2*start;j if (j+110e-6) {++j;} if (Temp<=sorted[j]) {break;} Sorted[start]=sorted[j]; s Tart=j; } sorted[start]=temp; }} public void Heapselectionsort (double [] sorted) {int sortedlen = sorted.length;

for (int i=sortedlen/2;i>0;i–) {heapadjust (Sorted,i,sortedlen);} for (int i=sortedlen;i>1;–i) {Exchange (sorted, 1,i); Heapadjust (sorted,1,i-1); }} public static void Main (String [] args) {Random random= new random (6);

int arraysize=9; Double [] sorted=new double[arraysize]; System.out.print ("Before Sort:"); for (int j=1;j<arraysize;j++) {sorted[j]= (int) (random.nextdouble () * 100); System.out.print ((int) sorted[j]+ "");} System.out.println ();

Selectionsort sorter=new Selectionsort (); Sorter.straitselectionsort (sorted); Sorter.heapselectionsort (sorted);

System.out.print ("After Sort:"); for (int j=1;j<sorted.length;j++) { system.out.print ((int) sorted[j]+ "");} System.out.println (); }} 7) Merge sort: Combine two or more two ordered tables into a new ordered table. Merge sort to use a secondary array, the same size as the original array, recursive procedure. Each time the target sequence is decomposed into two sequences, two sub-sequences are sorted, and two sorted sub-sequences are merge together. Merge sort Java code: public class MergeSort {private double[] bridge;//auxiliary array public void sort (double[] obj) {if (obj = = null) {thro W New NullPointerException ("The Param can not be null!"); } bridge = new Double[obj.length]; Initializes an intermediate array of mergesort (obj, 0, obj.length-1); Merge sort bridge = null; } private void MergeSort (double[] obj, int left, int. right) {if (left < right) {int center = (left + right)/2; MergeS ORT (obj, left, center); MergeSort (obj, center + 1, right); Merge (obj, left, center, right); }} private void merge (double[] obj, int left, int center, int right) {int mid = center + 1; int third = left; int tmp = L Eft while (left <= center && mid <= right) {//Remove small from two arrays into the middle array if (obj[left]-obj[mid]<=10e-6) {bridge[third+ +]= obj[left++]; } else{bridge[third++] = obj[mid++];}}

The remainder is placed in the middle array in turn (mid <= right) {bridge[third++] = obj[mid++],} while (left <= center) {bridge[third++] = obj[ Left++]; }//Copy the contents of the intermediate array back to the original array copy (OBJ, TMP, right); } private void Copy (double[] obj, int left, int. right) {while (left <= right) {Obj[left] = Bridge[left]; left++;}} P Ublic static void Main (string[] args) {Random random = new random (6);

int arraysize = 10; double[] sorted = new Double[arraysize]; System.out.print ("Before Sort:"); for (int j = 0; J < ArraySize; J + +) {Sorted[j] = (int) (random.nextdouble () * 100); System.out.print ((int) sorted[j] + "");} System.out.println ();

MergeSort sorter = new MergeSort (); Sorter.sort (sorted);

System.out.print ("After Sort:"); for (int j = 0; J < Sorted.length; J + +) {System.out.print ((int) sorted[j] + "");} System.out.println (); } }

8) Cardinal Sort: Using 10 auxiliary queues, assuming that the maximum number of digits is x, then do x times, starting from the single digit forward, based on the size of the number I digits, put the data into the auxiliary queue, after the recovery. The next one is based on a digit that starts at a higher position. Java code with Vector as auxiliary queue, base sort: public class Radixsort {private int keynum=-1; private vector<vector> util;

public void distribute (double [] sorted, int nth) {if (Nth<=keynum && nth>0) {util=new vector<vector> ( ); for (int j=0;j<10;j++) {vector temp= new vector  (), Util.add (temp);} for (int j=0;j<sorted.length;j++) {  int index= getnthdigit (sorted[j],nth); Util.get (Index). Add (Sorted[j]); }}} public int getnthdigit (double num,int nth) {String nn= integer.tostring ((int) num); int len= nn.length (); if (len>= Nth) {return Character.getnumericvalue (Nn.charat (Len-nth));} else{return 0;}} public void collect (double [] sorted) {int k=0, for (int j=0;j<10;j++) {int len= util.get (j). Size (), if (len>0) {for (i NT i=0;i<len;i++) { sorted[k++]= util.get (j). get (i);}} } util=null; } public int Getkeynum (double [] sorted) {Double max= double.min_value, for (int j=0;j<sorted.length;j++) { if (sor Ted[j]>max) {max= sorted[j];}} return integer.tostring ((int) max). Length (); } public void Radixsort (double [] sorted) {if (keynum==-1) {keynum= getkeynum(sorted); } for (int i=1;i<=keynum;i++) {Distribute (sorted,i); collect (sorted);}} public static void Main (string[] args) {Random random = new random (6);

int arraysize = 21; double[] sorted = new Double[arraysize]; System.out.print ("Before Sort:"); for (int j = 0; J < ArraySize; J + +) {Sorted[j] = (int) (random.nextdouble () * 100); System.out.print ((int) sorted[j] + "");} System.out.println ();

Radixsort sorter = new Radixsort (); Sorter.radixsort (sorted);

System.out.print ("After Sort:"); for (int j = 0; J < Sorted.length; J + +) {System.out.print ((int) sorted[j] + "");} System.out.println (); }} =====: In the above Java code, basically use a double array, if you want to apply the other array, only need to change the double array into an comparable interface array, all implementations of the comparable interface can be used. In C + +, the template class is used to solve this problem.

Java Sorting algorithm

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.