Seven Classic Sort (Java edition)

Source: Internet
Author: User

.

Bubble Sort:By the comparison of the adjacent two numbers, it is necessary to decide whether to swap the two number positions, and then forward (or backward) the comparison. The simplest sort algorithm, directly on the code.
 for (i=0;i<length-1;i++)      for (j=i+1;j<length;j++)     if (arrayval[i]>arrayval[j])     {             // Displacement position             temp=arrayval[i];             Arrayval[i]=Arrayval[j];             ARRAYVAL[J]=temp;         }}
View CodeSelect sort:"Select Sort" is the No. 0 step and the back of all the ratio, than the end of 0 positions to get the smallest number, and then from the 1-bit contrast behind the elements, and so on, gradually get from small to large values.
 for (int i = 0; i < arr.length-1; i++) {        int k = i;     for (int j = k + 1; j < Arr.length; J + +) {        if(Arr[j] < arr[k]) {        k =j;      }        // at the end of the inner loop, that is, after finding the smallest number of cycles, then swapping    if (i! = k) {     int temp= arr[i];    Arr[i] = arr[k];    ARR[K] = temp;    }
View CodeInsert Sort:First two data of the array is sorted from small to large.    The third data is then compared with two sorted data, and the third data is inserted into the appropriate position.    The fourth data is then inserted into the first 3 sorted data. ....
//The 1th number must be orderly, traversing from the 2nd number, inserting an ordered sequence sequentially          Public  Static voidInsertionsort (int[] a) {             for(inti = 1; i < a.length; i++){                            inttemp =A[i]; intj = I-1;  while(J >= 0 && Temp <A[j]) {A[j+1] =A[j]; J--; } a[j+1] =temp; }

Shell sorting algorithm: (Hill sort, narrow incremental sort): 

  Shell sorting is based on the idea of insertion sorting. 1. Divide the array of n elements into N/2 sequence of numbers, the 1th data and the n/2+1 data are a pair, ...2. A cycle allows each sequence to be sorted in order. 3. Then, change to N/4 sequence, in the second order. 4. Until the sequence becomes 1.
Hill sort Public Static voidShellsort (inta[]) {                     for(intR = A.LENGTH/2; R >= 1; r/=2 ){                             for(inti = r; i < a.length; i++){                                      inttemp =A[i]; intj = i-R;  while(J >= 0 && Temp <A[j]) {A[j+R] =A[j]; J-=R; } a[j+R] =temp; }          }     }

Fast sorting algorithm

1. The element to be sorted takes one element as the datum (usually the first element, but the most choice is to select one randomly from the element to be sorted as the Datum), which is called the datum element; 2. The element to be sorted is partitioned, and the element larger than the datum element is placed on its right, smaller than its left side;3. Repeat the above steps for the left and right two partitions until all elements are ordered.       
 Public Static voidQUICKSORT3 (intArr[],int_left,int_right) {                  intleft =_left; intright =_right; inttemp = 0; if(left <= right) {//There are at least two instances of the elements to be sortedTemp= Arr[left];//the first element to be sorted as a datum element             while(Left! = right) {//alternate scan from left to right                 while(Right > Left && arr[right] >=temp) { Right--;//scan from right to left to find the first element that is smaller than the base element} Arr[left]=Arr[right];  while(Left < right && Arr[left] <=temp) { Left++;//scan from left to right to find the first element larger than the base element} Arr[right]=Arr[left]; } Arr[right]= temp;//datum elements are returned to bitsQuickSort3 (arr,_left,left-1);//recursively sort elements to the left of a datum elementQuickSort3 (arr, right+1,_right);//recursively sort on the right side of a datum element                   }           }

Heap Sorting algorithm

   Heap sorting is a sort algorithm designed by using the data structure of heap, heap sort is a sort of choice, its worst, best, average time complexity is O (NLOGN), it is also unstable sort. Start with a simple understanding of the next heap structure. Heap:A heap is a complete binary tree with the following properties:the value of each node is greater than or equal to the value of its left and right child nodes, called the Big Top heap, or the value of each node is less than or equal to the value of its left and right child nodes, called the small top heap.

   

  The basic idea of heap sorting : to construct a sequence of orders to be a large top heap, at which point the maximum value of the entire sequence is the root node of the heap top. Swap it with the end element, which is the maximum value at the end. The remaining n-1 elements are then reconstructed into a heap, which gives the minor values of the n elements. With this repeated execution, an ordered sequence can be obtained.

Basic steps for heap sorting:

1. Construct the initial heap. Constructs the given unordered sequence into a large top heap (generally ascending with a large top heap, and descending with a small top heap).

2. Swap the top element of the heap with the end element to maximize the end element. Then continue to adjust the heap, and then swap the top element of the heap with the end element to get the second largest element. So repeated exchange, reconstruction, exchange.

   

 Public classHeapsort { Public Static voidMain (String []args) {int[]arr = {9,8,7,6,5,4,3,2,1};        Sort (arr);    System.out.println (arrays.tostring (arr)); }           Public Static voidSortint[]arr] {        //1. Build a large top heap         for(inti=arr.length/2-1;i>=0;i--){adjustheap (arr,i,arr.length); }                for(intj=arr.length-1;j>0;j--) {swap (arr,0,J); Adjustheap (ARR,0,J);        }    }    //Adjust the large top pile     Public Static voidAdjustheap (int[]arr,intIintlength) {        inttemp = Arr[i]; for(intk=i*2+1;k<length;k=k*2+1) {if(K+1<length && arr[k]<arr[k+1]) {k++; }            if(Arr[k] >temp) {//assigns the child node value to the parent node if the child node is greater than the parent nodeArr[i] =Arr[k]; I=K; }Else{                 Break; }} Arr[i]= temp;    }//Exchange element     Public Static voidSwapint[]arr,intAintb) {        inttemp=Arr[a]; Arr[a]=Arr[b]; ARR[B]=temp; }}
Merge Sortmerge Sort (merge-sort) is a sort method that is realized by merging thought, the algorithm uses the classical Divide and conquer (Divide-and-conquer) strategy (divide-and-conquer method to divide the problem (divide) into some small problems and then solve them recursively, while the Governance (conquer) The stage of the sub-phase will be the answer "patched" together, that is, divide and conquer).     
 Public classMergeSort { Public Static voidMain (String []args) {int[]arr = {9,8,7,6,5,4,3,2,1};        Sort (arr);    System.out.println (arrays.tostring (arr)); }     Public Static voidSortint[]arr] {        int[]temp =New int[Arr.length];//before sorting, build a temporary array of good one length equal to the original array length to avoid frequent space-opening in recursionSort (arr,0,arr.length-1, temp); }    Private Static voidSortint[] arr,intLeftintRightint[]temp] {        if(left<Right ) {            intMid = (left+right)/2; Sort (arr,left,mid,temp);//left-hand sub-sequence ordered by merge orderSort (arr,mid+1,right,temp);//Right merge sort to make right sub sequence orderlyMerge (Arr,left,mid,right,temp);//merging two ordered sub-arrays        }    }    Private Static voidMergeint[] arr,intLeftintMidintRightint[] temp) {        inti = left;intj = mid+1;intt = 0; while(I<=mid && j<=Right ) {            if(arr[i]<=Arr[j]) {temp[t+ +] = arr[i++]; }Else{temp[t+ +] = arr[j++]; }        }         while(I<=mid) {temp[t++] = arr[i++]; }         while(J<=right) {temp[t++] = arr[j++]; } t= 0; //copy all elements in temp to the original array         while(Left <=Right ) {Arr[left+ +] = temp[t++]; }    }}

Comparison of various sorting algorithms:

Sorting algorithms Average Worst case scenario is stable
Bubble sort O (n^2) O (n^2) Stability
Quick Sort O (NLOGN) O (n^2) Not stable
Select sort O (n^2) O (n^2) Not stable
Insert Sort O (n^2) O (n^2) Stability
Heap Sort O (NLOGN) O (NLOGN) Not stable
Shell sort O (n^ (3/2)) O (n^2) Not stable
Merge sort O (NLOGN) O (NLOGN) Stability

Seven Classic Sort (Java edition)

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.