Java programmers must know the 8 big sort

Source: Internet
Author: User
Tags pow stub

Download the document and own screenshots to preserve

The relationship between 8 sorts:


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;
 
public class 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];                       Move the value greater than the temp whole back 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

public class Shellsort {
public	Shellsort () {
	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 sort

(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



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; public class Heapsort {int a[]={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=dat
        A[i];
        DATA[I]=DATA[J];
    data[j]=tmp; //pairs of data array from 0 to lastindex build a large top heap private void Buildmaxheap (int[] data, int lastindex) {//TODO auto-generated 
            Method stub//starting with the parent node of the node (last node) at lastindex (int i= (lastIndex-1)/2;i>=0;i--) {//k Save the node being judged
            int k=i; If the child node of the current K node exists
            while (K*2+1<=lastindex) {The index int biggerindex=2*k+1 of the left child node of the//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
                    Record the index biggerindex++ of the larger child nodes;
                    }//If the value of K node is less than the value of its larger child node if (Data[k]<data[biggerindex]) {
                    Swap them 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 {
public	Bubblesort () {
	 int a[]={ 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

public class QuickSort {int a[]={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 QuickSort () {quick (a);
for (int i=0;i<a.length;i++) System.out.println (A[i]);    public int getmiddle (int[] list, int low, int high) {int tmp = List[low];   

      The first of the array is in the axis while (low < high) {while (Low < high && List[high] >= tmp) {   
	            high--;   } List[low] = List[high];   
	            A record that is smaller than the middle axis moves to the low-end while (Low < high && List[low] <= tmp) {low++;   } 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} public void _quicksort (int[] list, int low, int high) {if (Low < high) {  int middle = getmiddle (list, low, high); Divides the list array into _quIcksort (list, low, middle-1);       Recursive sorting of low word tables _quicksort (list, middle + 1, high);   
	            Recursively sort the high-word table} public void Quick (int[] A2) {if (A2.length > 0) {//See if 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; public class Mergingsort {int a[]={
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 Mergingsort () {sort (a,0,a.length-1);
for (int i=0;i<a.length;i++) System.out.println (A[i]);
        public void sort (int[] data, int left, int right) {//TODO auto-generated Method stub if (left<right) {
        Find the intermediate index 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); } public void Merge (int[] data, int left, int center, int right) {//TODO auto-generated method Stub int [] tmp
    Arr=new Int[data.length];
    int mid=center+1;
    Third the index int third=left of the intermediate array;
    int tmp=left; while (left<=center&&mid<=right) {//Remove from two arrays the smallest put in intermediate array if (Data[left]<=data[mid]) {T
        Mparr[third++]=data[left++];
          }else{  Tmparr[third++]=data[mid++];
    }//The remainder into the 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 {int a[]={
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 (int i=0;i<a.length;i++) System.out.println (A[i]);   
        The public void sort (int[] array) {//first determines the number of trips to be sorted;   
        int max=array[0];   
	           for (int i=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=new arraylist<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++) {           
	            Allocates an array element; 
	        	   for (int j=0;j<array.length;j++) {//Get number time+1 digits;
	        	   int x=array[j]% (int) Math.pow (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> Queu
	                    E3=queue.get (k);   
	                    Array[count]=queue3.get (0);
                    Queue3.remove (0);
              count++;
 }   
            }   
	}             
   }  

}



Related Article

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.