Diagram programmer must master the Java Common 8 big sort algorithm _java

Source: Internet
Author: User
Tags pow stub

This article mainly introduces how Java implements eight commonly used sorting algorithms: Insert sort, bubble sort, select Sort, hill sort, quick sort, merge sort, heap sort and lst cardinal order, and share for everyone to learn.

Classification
1 Insert Sort (direct insert sort, hill Sort)
2 Exchange sort (bubble sort, quick sort)
3 Select sort (Direct select sort, heap sort)
4) Merge sort
5) Allocation sort (cardinal sort)

Maximum required secondary space: merge sort
Minimum required auxiliary space: heap Sort
Average Speed fastest: quick sort

Instability: Quick sort, hill sort, heap sort.

Let's take a look at the relationship between 8 kinds of sorting:


1. Direct Insertion Sort

(1) Basic idea: In the set of numbers to be sorted, suppose that the front (n-1) [n>=2] number is already a row

In a good order, now you have to insert the nth number into the preceding ordered number so that the number of n

It's a good order, too. Repeat the loop until all the order is sorted.

(2) Example

(3) Implement with Java

Package Com.njue; 
 
Publicclass insertsort {public 
 
insertsort () { 
 inta[]={ 49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; 
 int temp=0; 
 for (int i=1;i<a.length;i++) { 
 int j=i-1; 
 Temp=a[i]; 
 for (; j>=0&&temp<a[j];j--) { 
  a[j+1]=a[j];//The value larger than the temp is moved one unit 
 } 
 a[j+1]=temp; 
 
 for (int i=0;i<a.length;i++) { 
 System.out.println (a[i]); 
 } 

2. Hill sort (minimum increment sort)

(1) Basic idea: The algorithm first will be sorted by a group of numbers by an increment D (n/2,n to the number of sorted numbers) into several groups, the subscript that is recorded in each group differs D. Inserts a direct sort of all elements in each group, and then groups it with a smaller increment (D/2). Make a direct insert sort in each group. When the increment is reduced to 1 o'clock, the sort completes after a direct insert sort.

(2) Example:


(3) Implement with Java

Publicclass Shellsort { 
 
publicshellsort () { 
 
 int a[]={1,54,6,3,78,34,12,45,56,100}; 
 Double d1=a.length; 
 int temp=0; 
 
 while (true) { 
 d1= Math.ceil (D1/2); 
 int d= (int) d1; 
 for (int x=0;x<d;x++) {for 
 
  (int i=x+d;i<a.length;i+=d) { 
  int j=i-d; 
  Temp=a[i]; 
  for (; j>=0&&temp<a[j];j-=d) { 
   a[j+d]=a[j]; 
  } 
  A[j+d]=temp 
  } 
 } 
 
 if (d==1) {break 
  ; 
 } 
 
 for (int i=0;i<a.length;i++) { 
 System.out.println (a[i]); 
 } 

3. Simple selection Sort

(1) Basic idea: In the number of groups to be sorted, select the smallest number and the number of the first position exchange;

Then, in the remaining number, find the smallest interchange with the second position, so that it loops to the penultimate number and the last number comparison.

(2) Example:


(3) Implement with Java

public class Selectsort {public 
 
 selectsort () { 
 int a[]={1,54,6,3,78,34,12,45}; 
 int position=0; 
 for (int i=0;i<a.length;i++) { 
  int j=i+1; 
  position=i; 
  int temp=a[i]; 
  for (; j<a.length;j++) { 
  if (a[j]<temp) { 
   temp=a[j]; 
   Position=j 
  } 
  } 
  A[position]=a[i]; 
  a[i]=temp; 
 } 
 
 for (int i=0;i<a.length;i++) 
  System.out.println (A[i]); 
 } 

4. Heap Sorting

(1) Basic idea: heap sort is a kind of tree-shape selection, which is an effective improvement to the direct selection sort.

The heap is defined as follows: A sequence with n elements (h1,h2,..., HN), which is called a heap only if it satisfies (hi>=h2i,hi>=2i+1) or (hi<=h2i,hi<=2i+1) (i=1,2,..., N/2). Only the heap that satisfies the former condition is discussed here. As you can see from the definition of the heap, the top element of the heap (that is, the first element) must be the maximum item (the large top heap). A complete binary tree can visually represent the structure of a heap. The top of the heap is the root and the other is Zuozi and right subtree. Initially, the sequence of numbers to be sorted is considered to be a sequential two-tree, which adjusts their storage order to make it a heap, at which point the number of root nodes of the heap is the largest. The root node is then exchanged with the last node of the heap. Then readjust the number of front (n-1) to make it a heap. And so on, until there are only two nodes in the heap, and exchange them, and finally get an ordered sequence of n nodes. From the description of the algorithm, heap sequencing requires two processes, one is to build a heap, and the other is to exchange positions between the top of the heap and the last element of the heap. So the heap sort has two function components. The first is to build the seepage function of the heap, and the second is to call the function of the infiltration function to realize the sort.

(2) Example:

Initial sequence: 46,79,56,38,40,84

Build heap:


Swap, kicking out the maximum number from the heap


Pile up the remaining nodes and swap the maximum number of kicks.


And so on: The last two remaining nodes in the heap are swapped, kicked out, sorted and finished.

(3) Implement with Java

Import Java.util.Arrays; Publicclass heapsort {inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51} 
 ; 
 Public Heapsort () {heapsort (a); 
 public void Heapsort (int[] a) {System.out.println ("start sort"); 
 int arraylength=a.length; 
  Loop build heap for (int i=0;i<arraylength-1;i++) {//Jian Yu buildmaxheap (a,arraylength-1-i); 
  Swap heap top and last element swap (a,0,arraylength-1-i); 
 System.out.println (Arrays.tostring (a)); 
 } private void Swap (int[] data, int i, int j) {//TODO auto-generated method stub int tmp=data[i]; 
 DATA[I]=DATA[J]; 
 data[j]=tmp; ///pairs of data array from 0 to lastindex build privatevoid buildmaxheap (int[] data, int lastindex) {//TODO auto-generated Method St 
  UB//starts with the parent node of the node (last node) lastindex (int i= (lastIndex-1)/2;i>=0;i--) {//k Saves the node int k=i that is being judged; 
  If the child node of the current K node exists the index int biggerindex=2*k+1 of the left child node of the while (K*2+1<=lastindex) {//k node; 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 larger if (Data[biggerindex]<data[biggerindex+1]) {//biggerindex always records the index biggerindex++ of the larger child node; 
   }//If the value of K node is less than the value of its larger child nodes if (Data[k]<data[biggerindex]) {//swap them for swap (DATA,K,BIGGERINDEX); 
  The Biggerindex is given K, the next loop of the while loop is guaranteed, and the value of K node is more than the value of the left and right child nodes k=biggerindex; 
  }else{break; } 
  } 
 } 
 } 
}

5. Bubble sort

(1) The basic idea: in order to sort of a group of numbers, the current has not yet lined up in the range of the total number of adjacent two numbers from top to bottom to compare and adjust, so that the larger number to sink, smaller upward. That is, whenever two adjacent numbers are compared and found to be in reverse order, they are interchanged.

(2) Example:

(3) Implement with Java

public class Bubblesort { 
 
Publicbubblesort () { 
 inta[]={ 49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; 
 int temp=0; 
 for (int i=0;i<a.length-1;i++) {for 
 (int j=0;j<a.length-1-i;j++) { 
  if (a[j]>a[j+1)) { 
  temp=a[j]; 
  A[J]=A[J+1]; 
  A[j+1]=temp 
 } 
 
 }} for (int i=0;i<a.length;i++) { 
 System.out.println (a[i]); 
 } 

6. Quick Sort

(1) Basic idea: Select a datum element, usually select the first element or the last element, through a scan, the backlog sequence is divided into two parts, one is smaller than the datum element, and the other is greater than or equal to the datum element, when the datum element is in its correct position, And then recursively sort the two parts of the partition in the same way.

(2) Example:


(3) Implement with Java

Publicclass QuickSort {inta[]={49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51 
}; 
 Publicquicksort () {quick (a); 
 for (int i=0;i<a.length;i++) {System.out.println (a[i]); 
  } publicint Getmiddle (int[] list, int low, int high) {int TMP =list[low];//The first of the array is the axis while (low < high) { 
  while (Low < high&& List[high] >= tmp) {high--; } List[low] =list[high]; 
  Moves to the low-end while (the low < high&& List[low] <= tmp) {low++) than the middle axis small record; } List[high] =list[low];  Higher than middle axis record to high end} List[low] = tmp;   Middle axis record to tail return low; Returns the position of the middle axis} publicvoid _quicksort (int[] list, int low, int high) {if (Low < high) {int middle =getmiddle (lis T, low, high); Divides the list array into _quicksort (list, low, middle-1); Recursive ordering of low word tables _quicksort (List,middle + 1, high);  Recursively sort the high-word table} publicvoid Quick (int[] A2) {if (A2.length > 0) {//See whether the array is empty _quicksort (a2,0, A2.length- 
  1); 
} 
}}
 

7. Merge sort

(1) Basic sort: Merge (merge) sorting method is to combine two (or more than two) ordered table into a new ordered table, that is, to divide the sequence into several subsequence, each subsequence is ordered. Then the ordered Subsequence is merged into the whole ordered sequence.

(2) Example:


(3) Implement with Java

Import Java.util.Arrays; Publicclass Mergingsort {inta[]={ 
 
49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,56,17,18,23,34,15,35,25,53,51}; 
 Publicmergingsort () {sort (a,0,a.length-1); 
for (int i=0;i<a.length;i++) System.out.println (A[i]); } publicvoid sort (int[] data, int left, int right) {//TODO Auto-generatedmethod stub if (left<right) {//Find middle Cable 
 Primer int center= (left+right)/2; 
 Recursive sort (data,left,center) on the left array; 
 Recursive sort (data,center+1,right) on the right array; 
 Merge and merge (Data,left,center,right); } publicvoid Merge (int[] data, int left, int center, int right) {//TODO auto-generatedmethod stub int [] tmp 
 Arr=newint[data.length]; 
 int mid=center+1; 
 Third the index int third=left of the intermediate array; 
 int tmp=left; while (left<=center&&mid<=right) {//removes from two arrays the smallest put in intermediate array if (Data[left]<=data[mid]) {tmparr[third++]= 
 Data[left++]; 
 }else{tmparr[third++]=data[mid++]; }//The remainder is placed in an intermediate array while (mid<=right) {Tmparr[thiRd++]=data[mid++]; 
 while (Left<=center) {tmparr[third++]=data[left++]; 
 //Copy the contents of the middle array back to the original array while (Tmp<=right) {data[tmp]=tmparr[tmp++]; 
} System.out.println (arrays.tostring (data));
 } 
}

8, Cardinal Order

(1) The basic idea: all the values to be compared (positive integer) unified to the same number of digits, the number of short digits before the number 0. Then, start at the lowest bit, and then sort it one at a time. This is done from the lowest bit to the highest order, and the sequence becomes an ordered series.

(2) Example:


(3) Implement with Java

Import java.util.ArrayList; 
 
Import java.util.List; public class Radixsort {inta[]={ 
 49,38,65,97,76,13,27,49,78,34,12,64,5,4,62,99,98,54,101,56,17,18,23,34,15,35,25,53,51}; 
 Public Radixsort () {sort (a); 
 for (inti=0;i<a.length;i++) {System.out.println (a[i]); 
 } public void sort (int[] array) {//first determines the number of trips to be sorted; 
 int max=array[0]; 
  for (inti=1;i<array.length;i++) {if (Array[i]>max) {max=array[i]; 
 } int time=0; 
 Determine the number of digits; 
  while (max>0) {max/=10; 
 time++; 
 //Establish 10 queues; 
 List<arraylist> queue=newarraylist<arraylist> (); 
  for (int i=0;i<10;i++) {arraylist<integer>queue1=new arraylist<integer> (); 
 Queue.add (queue1); 
 //Time allocation and collection; 
  for (int i=0;i<time;i++) {//assign array element; 
   for (intj=0;j<array.length;j++) {//Get number time+1 digits; 
   int x=array[j]% (int) Math.pow (10,i+1)/(int) Math.pow (i); 
   Arraylist<integer>queue2=queue.get (x); 
   Queue2.add (Array[j]); 
  Queue.set (x, queue2); } INT count=0;//element counter; 
  Collect queue elements; 
   for (int k=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++;

 } 
  } 
 }  
 } 
}

The above is the entire content of this article, I hope to help you learn.

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.