Eight kinds of sorting algorithms for Java----

Source: Internet
Author: User

1. Direct Insert Sort

This sort of problem is often encountered: inserting new data into rows that have already been sorted.

Sorts the first and second numbers and then forms an ordered sequence

The third number is inserted to form a new ordered sequence.

The fourth number, the fifth number ... Until the last number, repeat the second step.

How to Write code:

First set the number of inserts, that is, the number of cycles, for (int i=1;i<length;i++), 1 number of the time without inserting.

Sets the number of inserts and the number of digits that are the last number of the sequence that has been ranked. Insertnum and J=i-1.

Loops forward from the last number, and moves the current number one bit backwards if the number of insertions is less than the current number.

Places the current number in an empty position, that is, j+1.

The code is implemented as follows:

2. Hill sort

For a direct insert sorting problem, the amount of data is huge.

Set the number of numbers to N, take odd k=n/2, and divide the book of the subscript difference to K into a group, forming an ordered sequence.

After taking K=K/2, the book dividing the subscript difference to K is divided into a group, which forms an ordered sequence.

Repeat the second step until K=1 performs a simple insert sort.

How to Write code:

First determine the number of groups to divide.

The elements in the group are then inserted into a sort order.

Then LENGTH/2, repeat 1, 2 steps until length=0.

The code is implemented as follows:

3. Simple selection of sorting

Often used to fetch the largest and smallest number of numbers in a sequence.

(if each comparison is exchanged, then it is an exchange sort; If you compare one cycle to another, it is simple to select the sort.) )

Traverse the entire sequence, placing the smallest number at the front.

Traverse the remainder of the sequence, placing the smallest number at the front.

Repeat the second step until there is only one number left.

How to Write code:

First determine the number of loops, and remember the current number and current position.

Compares all the numbers after the current position to the current number, assigns a decimal value to key, and remembers the position of the decimal.

When the comparison is complete, the minimum value is exchanged with the value of the first number.

Repeat steps 2, 3.

The code is implemented as follows:

4. Heap Sequencing

The optimization of simple selection sorting.

Build the sequence into a large top heap.

Swaps the root node with the last node, and then disconnects the last node.

Repeat the first to second step until all the nodes are disconnected.

The code is implemented as follows:

 Public  voidHeapsort (int[] a) {System.out.println ("Start sorting"); intArraylength=a.length; //Loop Build Heap        for(inti=0;i<arraylength-1;i++){           //Build a heapBuildmaxheap (A,arraylength-i); //swap heap top and last elementSwap (a,0,arraylength-1-i);       System.out.println (Arrays.tostring (a)); }   }   Private  voidSwapint[] Data,intIintj) {//TODO auto-generated Method Stub       inttmp=Data[i]; Data[i]=Data[j]; DATA[J]=tmp; }   //build a large top heap from 0 to lastindex for the data array   Private voidBuildmaxheap (int[] Data,intLastIndex) {       //TODO auto-generated Method Stub//starting at the parent node of the lastindex node (the last node)        for(intI= (lastIndex-1)/2;i>=0;i--){           //K Save the node being judged           intk=i; //If the child node of the current K-node exists            while(k*2+1<=LastIndex) {               //index of the left child node of the K-node               intBiggerindex=2*k+1; //if Biggerindex is less than lastindex, that is, the right child node of the K node represented by biggerindex+1 exists               if(biggerindex<LastIndex) {                   //If the value of the right child node is large                   if(data[biggerindex]<data[biggerindex+1]){                       //Biggerindex always records the index of a larger child nodebiggerindex++; }               }               //if the value of the K-node is less than the value of its larger child nodes               if(data[k]<Data[biggerindex]) {                   //Exchange themswap (Data,k,biggerindex); //Assign the Biggerindex to K, start the next loop of the while loop, and re-guarantee that the value of the K-node is greater than the value of its left and right child nodesk=Biggerindex; }Else{                    Break; }           }       }   }

5. Bubble sort

Generally not.

Compares all elements in a sequence to 22, placing the largest in the last face.

Compares all elements in the remaining series to 22, placing the largest in the last face.

Repeat the second step until there is only one number left.

How to Write code:

Sets the number of cycles.

Sets the number of bits to start comparing, and the number of bits to end.

22 Compare, put the smallest to the front.

Repeat steps 2 and 3 until the number of loops is complete.

The code is implemented as follows:

6. Quick Sort

Ask for the fastest time.

Select the first number is p, the number less than P is on the left, and the number greater than P is on the right.

Recursively, the left and right numbers of P follow the first step until they are not recursive.

The code is implemented as follows:

7. Merge sort

The speed is second only to the fast row, when the memory is low, it can be used in parallel computation.

Select two adjacent numbers to form an ordered sequence.

Select two contiguous sequential sequences to form an ordered sequence.

Repeat the second step until the whole sequence is formed.

The code is implemented as follows:

 Public Static voidMergeSort (int[] numbers,intLeftintRight ) {     intt = 1;//number of elements per group   intSize = Right-left + 1;  while(T <size) {         ints = t;//number of elements per group in this cyclet = 2 *s; inti =Left ;  while(i + (t-1) <size) {Merge (numbers, I, I+ (s-1), i + (t-1)); I+=T; }         if(i + (s-1) <Right ) Merge (numbers, I, I+ (s-1), right); }  }  Private Static voidMergeint[] Data,intPintQintr) {int[] B =New int[Data.length]; ints =p; intt = q + 1; intK =p;  while(s <= q && t <=r) {if(Data[s] <=Data[t]) {B[k]=Data[s]; S++; } Else{B[k]=Data[t]; T++; } k++; }     if(s = = q + 1) B[k+ +] = data[t++]; Elseb[k+ +] = data[s++];  for(inti = P; I <= R; i++) Data[i]=B[i]; }

8. Base sorting

Used for a large number, when a long number is sorted.

The single digit of all the numbers is taken out, sorted by one-digit number, forming a sequence.

The 10-digit number of all the newly constituted numbers is taken out and sorted by 10 digits to form a sequence.

The code is implemented as follows:

 Public voidSortint[] Array) {       //first, the number of sorts is determined;        intmax = Array[0];  for(inti = 1; i < Array.Length; i++) {           if(Array[i] >max) {Max=Array[i]; }       }       intTime = 0; //determine the number of digits;         while(Max > 0) {Max/= 10; time++; }       //set up 10 queues; list<arraylist> queue =NewArraylist<arraylist>();  for(inti = 0; I < 10; i++) {ArrayList<Integer> queue1 =NewArraylist<integer>();       Queue.add (queue1); }       //time allocation and collection;         for(inti = 0; I < time; i++) {           //assigning array elements;             for(intj = 0; J < Array.Length; J + +) {               //get the number of time+1 digits;                intx = array[j]% (int) Math.pow (Ten, i + 1)/(int) Math.pow (10, i); ArrayList<Integer> queue2 =queue.get (x);               Queue2.add (Array[j]);           Queue.set (x, queue2); }           intCount = 0;//element counter; //collect queue elements;             for(intk = 0; K < 10; k++) {                while(Queue.get (k). Size () > 0) {ArrayList<Integer> Queue3 =Queue.get (k); Array[count]= Queue3.get (0); Queue3.remove (0); Count++; }           }       }

----[transfer from public number]

Eight kinds of sorting algorithms for Java----

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.