Java Common sorting algorithm

Source: Internet
Author: User

In the sort process, all records are stored in memory, which is called an inner sort, and is called an out-of-order if you need to use external memory during sorting.

In general, out-of-order is divided into two steps: preprocessing and merge sorting. First, according to the size of available memory, the files containing N records on external memory are divided into sub-files (or segments) of length T, and secondly, the T-Records of each sub-file are sorted internally by the method of internal sorting. These sorted sub-files (segments) are often referred to as a string (run), which is written to external memory after the string is generated. This gives the M-string (m=[n/t]) on the external memory. Finally, the strings are merged, so that the length of the string increases gradually until all the probabilities to be sorted become a straight string.

The inner sort can be divided into the following categories:

(1), insert Sort: Direct insert sort, binary insert sort, hill sort.

(2), select Sort: Simple select sort, heap sort.

(3), Exchange sort: bubble sort, quick sort.

Out-of-order can be divided into several categories (using both internal storage and external storage, which is recommended when memory is insufficient):

(4), merge sort

(5), base sort

Stability: It is guaranteed to sort the first two equal data in the sequence with the order of their precedence and the order of their two successive positions. Again, if a i = = a j,ai originally before the AJ position, the Ai is still in front of the AJ position.

Instability: Simple selection of sorting, quick sorting, hill sorting, heap sorting is not a stable sorting algorithm

Stability: Bubble sort, direct insert sort, binary insert sort, merge sort and cardinal sort are all stable sorting algorithms.

Average Time complexity

O (n^2): Direct insert Sort, simple select sort, bubble sort.

In the case of small data size (9W), the direct insertion of the sort, simple selection of sort almost. The bubbling sorting algorithm has the highest time cost when the data is large. The Performance O (n^2) algorithm is basically a comparison of adjacent elements, which are basically stable.

O (NLOGN): Quick Sort, merge sort, hill sort, heap sort.

Among them, the fastest row is the best, followed by the merger and Hill, heap sorting in the data is very large when the effect is obvious.

First, insert sort

? idea: Each step inserts a backlog of records into the appropriate position of the ordered sequence of characters by its sequential code size until all insertions are sorted out.
Key question: Find the right insertion position in the sequence that is already sorted in front of you.
Method
– Direct Insert Sort
– Binary Insert Sort
– Hill Sort

1. Direct Insert sort legend: Key code:
private static void Directinsertsort (int[] array) {for       (int. i=0;i<array.length;i++) {for             (int j=0;j<i;j+ +) {                if (Array[i]<array[j]) {                    int temp=array[i];                    System.arraycopy (array,j,array,j+1,i-j);                    array[j]=temp;}}}}       

2. Binary insertion sort (dichotomy insertion sort) binary insertion sort (binary insertion sort) is an improvement to the insertion sorting algorithm, which, because of the sequencing algorithm, inserts the elements sequentially into the sequential sequence. Since the first half of the sequence is already ordered, we do not need to find the insertion point sequentially, and we can use the binary lookup method to speed up the search for the insertion point. Legend: Key Code:
private static void Binaryinsertsort (int[] array) {for    (int i=1;i<array.length;i++) {     int tempdata=array[i] ;     int low=0;     int high=i-1;     while (Low<=high) {         int middle= (Low+high)/2;         if (array[middle]<tempdata)             low=middle+1;         else             high=middle-1;     }     System.arraycopy (array,low,array,low+1,i-low);     Array[low]=tempdata;}    }
3. Hill Sort Hill sort (Shell sort) is one of the insertion sort, is the improvement of the direct insertion sorting algorithm, is to divide the entire sequence into a number of small sub-sequences to be inserted sort, the hill sort is not stable. This method is also known as narrowing the incremental sort, because of the DL. The shell was named after it was introduced in 1959. The worst-case number of compares used by Shellsort withthe 3x+1 increments is O (N 3/2).

Legend:

Key code:
/** * Shell Sorting algorithm * Incremental h= (h*3) +1; This increment formula is given by Knuth * If you do not know it well, please Baidu. * @param array */private static void Shellsort (int[] array) {   //First determine the maximum value of the increment based on the length of the array C1/>int h=1;   Press H * 3 + 1 to get the maximum value of the increment sequence   while (H <= array.length/3)       h = h * 3 + 1;   Incremental find and sort while   (h>=1) {for              (int i=h;i<array.length;i++) {for   (int j=i;j >= h && array[j ] < array[j-h];j-= h) {   int temp = array[j];   ARRAY[J] = array[j-h];   ARRAY[J-H] = temp;   }   }   h = H/3;   } }
Second, choose the sort? thought: Each trip from the record sequence to be sorted, select the record that has the smallest keyword to be placed in the top position of the sorted table until all rows are completed. Key issue: Find the minimum key code record in the remaining sequence of records to be sorted. Method: – Direct selection of the sort – Heap sort 1. Direct selection sort in the number of groups to be sorted, select the smallest number to be exchanged with the first position, and then in the remaining number to find the smallest and second position of the number of exchanges, so loop to the penultimate number and the last number comparison. Legend: Key Code:
public static void Directselectionsort (int[] array) {for (int. i=0;i<array.length-1;i++) {for        (int j=i+1;j< array.length;j++) {            if (Array[i]>array[j]) {            int temp = array[i];            Array[i] = array[j];            ARRAY[J] = temp;            }                       } }}

2. When the heap is initially sorted, the sequence of the numbers to be sorted is considered as a two-fork tree in sequential storage, which adjusts their storage order to become a heap, when the heap has the largest number of root nodes. The root node is then exchanged with the last node of the heap. The number of fronts (n-1) is then re-adjusted to make it a heap. And so on, until there are only two nodes of the heap, and exchange them, and finally get an ordered sequence of n nodes. Heap ordering is also an unstable sorting algorithm.

Heap sorting is better than simple selection of the reason: in the direct selection of the sorting, in order to select from the R[1..N] the smallest record of the keyword, you must make a n-1 comparison, and then in R[2..N] to select the smallest record of the keyword, but also need to do n-2 comparison. In fact, there are a number of comparisons that are likely to have been made in the previous n-1 comparison, but because the previous n-2 did not retain these comparisons, the comparison was performed repeatedly when the latter was sorted. Heap sorting saves some of the comparison results by using a tree structure, which reduces the number of comparisons. The worst time complexity for heap sorting is O (Nlogn). The average performance of the heap is closer to the worst performance. Heap sorting is not appropriate for files with fewer records due to the number of comparisons required to build the initial heap.

Legend: Build heap: Swap, kick the last number out of the heap: Key code:
public static void Buildminheap (int[] array) {for (int. i=array.length-1;i>0;i--) {for (int j= (i-1)/2;j>=0;j--) {// I is odd, there is only one leaf node    if ((2*j+1==i) && (i%2!=0)) {    if (array[j]<array[2*j+1])    swap (array,j,2* j+1);    } else{    if (array[j]<array[2*j+1])        swap (array,j,2*j+1);        if (array[j]<array[2*j+2])            swap (array,j,2*j+2);    }   }   Swap (array,0,i);}    } private static void Swap (int[] Array,int i,int j) {int temp=array[i];array[i]=array[j];array[j]=temp;}

  

Iii. Exchange sort 1. Bubble sort legend:
Key code:
public static int[] Bubblesort (int[] array) {if (array = = NULL) return Array;int len = array.length;for (int i = len-1; I &G T 0;  i--) {for (int j = 0; J < i; J + +) {if (Array[j] > array[j + 1]) {int temp = Array[j];array[j] = array[j + 1];array[j + 1] = temp;}}} return array;}

  

Analysis:

Bubble sort is a stable sort method.

If the first form of the file is a positive sequence, then a trip to the bubble can be sorted, sorting code is n-1, and there is no record movement, the time complexity is O (n)? If the file is in reverse order, it is necessary to n-1, each trip to n-i the comparison of the order code, and each time the comparison is moved three times, Maximum number of comparisons and moves: O (n2)? Bubble sort Average time complexity is O (N2) 2. Quick sort selects a datum element, usually selects the first element or the last element, and, through a scan, divides the pending sequence into two parts, a portion smaller than the datum element, and a portion greater than or equal to the datum element. At this point the datum element is in the correct position after it is ordered, and then the same method is used to sort the two parts recursively. Traditional method Legend: Key code:
public static void QuickSort (int[] array,int Start,int end) {    if (start==end)        return;    int i=start+1;    int j=end;    while (I<J) {for               (; array[i]<array[start]&&i<j;i++);    for (; array[j]>array[start]&&j>i;j--);    Swap (ARRAY,I,J);      }    if (Array[i]<array[start])        swap (array,i,start);    QuickSort (array,start,i-1);    QuickSort (array,i,end);} public static void Swap (int[] array, int i, int j) {    int temp = array[i];    Array[i] = array[j];    ARRAY[J] = temp;}

  

Analysis:

Quick Sort is an unstable sort.

The time complexity for quick sorting is O (Nlogn).

When n is larger, it is better to use fast parallelism, but it is not good to use fast platoon when the sequence is basically ordered.

The merge sort merge (merge) sorting method is to combine two (or more than two) ordered tables into a new ordered table, that is, to divide the ordered sequence into several sub-sequences, each of which is ordered. Then the ordered subsequence is combined into a whole ordered sequence. Legend: Key Code:
private static void sort (int[] array,int Low,int high) {if (Low < high) {Int. middle= (low + high)/2;//recursive processing related merge matters    sort (Array,low,middle);    Sort (array,middle+1,high);    Merge (Array,low,middle,high);}            } private static void merge (int[] array, int low, int middle, int. high) {//Create a temporary array to store the merged data int[] Temp=new int[array.length ];int i = low;int j = Middle+1;int k = low;while (i <= Middle && J <= High) {if (Array[i]<array[j]) temp[k++] =array[i++];    else    temp[k++]=array[j++];} Process the remaining unincorporated portions while (I <= middle)    Temp[k++]=array[i++];while (J <= High)    temp[k++]=array[j++];// Stores the contents of the temporary array in the original array while (Low <= high)    array[low]=temp[low++];}   

  

Analysis:

Merge sort is a stable sorting method.

The time complexity of the merge sort is O (Nlogn).

The speed is second only to the fast order, the stable sort algorithm, is generally used for the total disorder, but each sub-item is relatively orderly sequence.

The Cardinal sort unifies all the values to be compared (positive integers) to the same digit length, and the number of short digits is preceded by 0. Then, start with the lowest bit and order one at a time. Thus, from the lowest bit to the highest order, the sequence becomes an ordered series. Legend: Key Code:
public static int[] Radixsort (int[] array) {//finds the maximum number, determines how many trips to sort int max = 0;            for (int i = 0; i < Array.Length; i++) {if (max<array[i]) max = Array[i];          }//Determine the number of digits int times = 0;              while (max>0) {max = MAX/10;          times++;           }//Establish 10 queues list<arraylist<integer>> alist = new arraylist<arraylist<integer>> ();              for (int i = 0; i < i++) {arraylist<integer> queue = new arraylist<integer> ();          Alist.add (queue); }//Times allocation and collection for (int i = 0; I < times; i++) {//assign for (int j = 0; J & Lt Array.Length;                 J + +) {int x = array[j]% (int) Math.pow (ten, i+1)/(int) Math.pow (ten, I);              Alist.get (x). Add (Array[j]);              }//Collect int count = 0; for (int j = 0; j < j+;+) {arraylist<integer> queue = Alist.get (j);                 while (Queue.size () >0) {array[count++] = queue.remove (0);      }}} return array;   }

 

Analysis:

The Cardinal sort is a stable sorting algorithm.

The time complexity of the radix sort is O (d (n+r)), D is the number of bits, and R is the cardinality.

Summary: The basic work is not used but the interview often test the algorithm problem. A temporary assault before the test.

Java Common 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.