Performance comparison of various sorting algorithms

Source: Internet
Author: User
Tags sorts

Insert Sort includes direct insert sort, hill sort .

1. Direct Insert Sort:

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:

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class insertsortdirectly {public    static void Insertsort (int[] a) {        int length = a.length;//Seek out length is to increase the speed of        int insertnum;        for (int i=1;i<length;i++) {//number to insert            Insertnum = a[i];            int j = i-1;            while (J>=0&&insertnum<a[j]) {                a[j+1] = a[j];                j--;            }            For example, 3 6 5, when J is found at 3, insert 5 in the j+1 position.            a[j+1]=insertnum;        }    }    public static void Main (string[] args) {        int[] a= {3,6,5};        Insertsort (a);        System.out.println (Arrays.tostring (a));}    }

Direct insertion of the sorting, the best case is that the data element has been all sequenced, then the number of internal cycles is 0, the number of external cycles is n-1, so the best case time complexity is O (N). The worst case scenario is that the original data element set is reversed, and at this point the loop count of the inner while loop in the algorithm is always I. Therefore, in the worst case, the time complexity is O (n^2). The spatial complexity of the direct insertion sort is O (1), and it is obvious that the direct insertion sort is a stable sorting algorithm.

2. Hill Sort:

          

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class Sheelsort {public    static void Sheelsort (int[] a) {        int d = a.length;        while (d!=0) {            d = D/2;            for (int x = 0; x < D; + +) {//Sub-group for                (int i=x+d; i<a.length; i=i+d) {//element in group, starting from 2nd                    int j = i-d;//j for ordered sequence last The number of digits                    int temp = a[i];//element to be inserted for                    (; j>=0&&temp<a[j]; j=j-d) {                        A[j+d] = a[j];//Move backward D-bit                    }< C11/>A[J+D] = temp;    }}}} public static void Main (string[] args) {        int[] a ={592,401,874,141,348,72,911,887,820,283};        Sheelsort (a);        System.out.println (Arrays.tostring (a));}    }

Hill sort, although using a four-cycle, but in fact, the first two layers of the cycle is very few, the latter two layers are directly inserted in the order, because the Hill sort group of data basically orderly, so the internal direct insertion sort quickly lined up. So, the time complexity of the hill sort is O (nlbn), the space complexity is O (1), because the hill sort algorithm is sorted by the increment grouping, so the hill sort is an unstable sort algorithm. In the case of 5,1,1,5, if the step size is 2, two 1 relative positions are exchanged.

Select Sort includes direct selection of sorting and heap sorting.

3. Direct selection of sorting

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class selectsortdirectly {public    static void Selectsort (int[] a) {        int len = a.length;        int minindex,temp;        for (int i=0;i<len-1;i++) {            minindex = i;            for (int j=i+1;j<len;j++) {                if (A[j]<a[minindex]) {                    minindex = j;                }            }            temp = A[i];            A[i] = A[minindex];            A[minindex] = temp;        }    } public static void Main (string[] args) {    int[] a ={592,401,874,141,348,72,911,887,820,283};    Selectsort (a);    System.out.println (Arrays.tostring (a));}    }

The time complexity of direct selection sorting is O (n^2), and the spatial complexity is O (1), which is an unstable sorting algorithm. For example 2 2 2 1, so that the minimum number 1 and the first 2 exchange, then the relative position of 2 has changed. If the smallest record is selected, the unordered record in front of it is shifted back, then the minimum record is placed behind the ordered area, which guarantees the stability of the sorting algorithm.

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.

Heap sorting key to understand, from the bottom up, adjust the node, for example, the tree altogether 3 layers, then the 2nd layer of the tree as the root node, to ensure that its sub-nodes are smaller than it, at this time, if the 1th layer is adjusted, if the left node is the maximum value, will be the first layer of the root node and the left To ensure that the 1th tier satisfies the structure of the maximum heap, it is possible to break the maximum heap structure of the left node of the 1th layer, so the heap of the left node of this 1th layer needs to be re-adjusted. -------------This is the key to understand!

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class Heapsort {public Heapsort () {}         public static 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); }} private static void Swap (int[] data, int i, int j) {//todo auto-generated method stub int tmp         =data[i];         DATA[I]=DATA[J];     data[j]=tmp; }//to the data array from 0 to LastIndex build a large top heap private static void Buildmaxheap (int[] data, int lastIndex) {//From the LastIndex node (             The parent node of the last node) starts for (int i= (lastIndex-1)/2;i>=0;i--) {//k Saves the node being judged int k=i; If the child node of the current K node exists while (K*2+1<=lastindex) {//k The index of the left child node of the node int biggerindex=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 right child node                         A value larger if (Data[biggerindex]<data[biggerindex+1]) {//biggerindex always records the index of a larger child node                     biggerindex++;                     }}//If the value of the K-node is less than the value of its larger child node if (Data[k]<data[biggerindex]) {                     Swap them swap (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 nodes//If you do not understand, then use the break point of the way to run, you can find that when i=0, because node 1 and node 0 Exchange                 , so it is necessary to readjust the heap structure of 1 nodes to ensure that the value of//1 node is still greater than the value of its left and right nodes K=biggerindex;                 }else{break;         }}}} public static void Main (string[] args) {int a[] = {7,13,6,43,5,23,4};         Heapsort (a);     System.out.println (Arrays.tostring (a)); }}

Heap sorting algorithm is based on a complete binary tree sorting, its time complexity is O (NLBN), its spatial complexity is O (1), heap sorting is an unstable sorting algorithm, such as 5 5 5, so that the largest heap is constructed, the 1th 5 and the last 5 to be exchanged, so, heap sorting is an unstable sorting algorithm.

the method of sorting with the location of the interchange data element is the interchange sort. The usual exchange sort has a bubbling sort and a quick sort. Fast sorting is a sort of partition switching method.

5. Bubble sort

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.

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class Bubblesort {public    static void Bubblesort (int[] a) {        Boolean issorted = true;         for (int i=0;i<a.length-1&&issorted;i++) {            issorted = false;             for (int j=0;j<a.length-1-i;j++) {                if (a[j]>a[j+1]) {                    int temp = a[j];                    A[J] = a[j+1];                    A[J+1] = temp;                    issorted = true;//Inner Loop If an interchange occurs, the proof continues to be sorted                }            }            //If the order has been sorted after 1 trips, then the 2nd trip ends, issorted = false; At this time,            // The outer loop can end prematurely based on the issorted status of the tag.        }    }        public static void Main (string[] args) {        int[] a ={592,401,874,141,348,72,911,887,820,283};        Bubblesort (a);        System.out.println (Arrays.tostring (a));}    }

The time complexity of the bubble sort is O (n^2), the space complexity is O (1), and the bubble sort is a stable sorting algorithm.

Fast sorting is a kind of binary tree structure Exchange sorting method.

6. Quick Sort

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class QuickSort {/*** Finds the middle axis (the default is the lowest bit low) in the position after the numbers array is sorted * * @param numbers with find array * @param low start position * @param high end position * @return Axis location * * Public static int getmiddle (int[] numbers, int low,int high) {int temp = Numbers[low];//The first of the array as the middle axis while the low <            High) {When (Low < high && Numbers[high] > Temp) {high--;  } if (Low

Quick sort if the standard element selected every time can be divided into two sub-array interval length, such a fast sorting process is a complete binary tree structure. In the best case, the time complexity of the fast sorting algorithm is O (NLBN). Fast sorting The worst case scenario is that the data elements are all ordered, and the number of decomposition times of the root node of the array constitutes a binary degenerate tree, so the time complexity of the worst-case fast sorting algorithm is O (n^2).

Because the fast sorting algorithm requires the stack space to temporarily save recursive call parameters, the number of stack space used and the number of recursive calls concerned, because the binary tree is likely to be a single two-fork tree, and a single two-fork tree depth of n-1, so the worst-case fast sorting algorithm space complexity is O (n).

7. Merge sort

Package Zhouls.bigdata.datafeatureselection;import Java.util.arrays;public class MergeSort {/** * Merge sort * Introduction: Merging two (or more than two) ordered tables into a new ordered table divides the ordered sequence into several sub-sequences, each of which is ordered. Then the ordered Subsequence is merged into the whole ordered sequence * time complexity O (NLOGN) * Stable sorting method * @param nums array to be sorted * @return Output ordered array */public static int[] sort (int[] Nu         MS, int low, int.) {int mid = (low + high)/2;             if (Low < high) {//left sort (nums, low, mid);             Right sort (nums, mid + 1, high);         Merge merges Around (Nums, low, Mid, high);     } return nums;         public static void Merge (int[] nums, int. Low, int mid, Int. high) {int[] temp = new Int[high-low + 1];         int i = low;//left pointer int j = mid + 1;//right pointer int k = 0;                 Move the smaller number first to the new array while (I <= mid && J <= High) {if (Nums[i] < nums[j]) {             temp[k++] = nums[i++];             } else {temp[k++] = nums[j++];  }       }//Move the left remaining number into the array while (I <= mid) {temp[k++] = nums[i++];         }//Move the remaining number in the right side into the array while (J <= High) {temp[k++] = nums[j++];         }//Overwrite the number in the new array with the Nums array for (int k2 = 0; K2 < temp.length; k2++) {nums[k2 + low] = Temp[k2]; }}//merge sort implementation public static void main (string[] args) {int[] Nums = {2, 7, 8, 3, 1, 6, 9, 0, 5, 4         };         Mergesort.sort (nums, 0, nums.length-1);     System.out.println (arrays.tostring (nums)); } }

The time complexity of the merge sort is O (nlbn), because the merge sort uses n temporary memory units to hold data elements, so the spatial complexity of the merge sort algorithm is O (n).

Merge sort is a kind of stable sorting algorithm. The previous time complexity is O (nlbn) sorting algorithm is an unstable sorting algorithm, and the merge sorting algorithm is not only the time complexity of O (NLBN), but also a stable sorting algorithm. This is the biggest feature of the merge sort algorithm.

8. Base Order

The cardinality is ordered because the data elements in and out of the bucket are required to meet the principle of first in, first out, so the bucket is actually a queue.

Package Zhouls.bigdata.datafeatureselection;import java.util.arrays;/** for an int array, write a cardinal sort algorithm that sorts the array elements. * Given an int array A and the size of the array n, return the sorted array. The guaranteed element is less than or equal to 2000. * Test Sample: [1,2,3,5,2,3],6[1,2,2,3,3,5]*/public class Radissort {//Everyone install public static int[] Radixsort (int[] A, int n)         {//First to determine the number of sorts of trips;         int max=a[0];             for (int i=1;i<n;i++) {if (A[i]>max) {max=a[i];         }} int time=0;         Determine the number of digits;             while (max>0) {max/=10;         time++;        } int length = n;        int divisor = 1;//defines the divisor of each round, 1,10,100 ...        int[][] Bucket = new int[10][length];//defines 10 buckets, in case every bit is the same all in one bucket int[] count = new int[10];//count the number of elements actually stored in each bucket int digit;//Gets the number on the corresponding bit in the element, that is, the bucket for (int i = 1; I <= time; i++) {//After 4 pass-through operation, sort complete for (int temp:                A) {//calculate into barrels digit = (temp/divisor)% 10;            bucket[digit][count[digit]++] = temp; } int k = 0;//the subscript for the sorted array for (int b = 0; b < b++) {//from 0 to 9th barrels in order to remove if (count[b] = = 0)//If there are no elements in this bucket                Into, then skip continue;                for (int w = 0; w < count[b]; w++) {a[k++] = bucket[b][w];        } Count[b] = 0;//The elements in the bucket have all been removed, the counter is zeroed} divisor *= 10;    } return A;    } public static void Main (string[] args) {int a[] = {1,2,3,5,2,3};    System.out.println (Arrays.tostring (Radixsort (A, a.length)); }}

Cardinality sorting time complexity is O (MN), M is the maximum number of digits, because the radix sorting algorithm to M times to use n nodes temporarily hold n data elements, therefore, the spatial complexity of the cardinality sorting algorithm is O (n).

Cardinality sorting is a stable sorting algorithm.

Summarize:

Sort by internal sort and external sort two kinds. internal sorting refers to the sort of all incoming data elements being transferred into memory. If the number of data elements is too large, it needs to be imported into memory in batches. Sequential import of data elements in memory is ordered and then exported to disk by batch method is called an external sort . The two sorting algorithms have the same principle, but the reading and writing speed in memory differs greatly from the reading and writing speed of the external storage, so the evaluation criteria are very different. Only internal sorting is discussed here.

Criteria for ranking algorithms:

1. Complexity of time.

2, Space complexity: The number of secondary storage space used in the algorithm. When the secondary storage space used in the sorting algorithm is independent of the number of data elements to be sorted, the spatial complexity is O (1).

3, stability.

Performance comparison of various sorting algorithms:

Sorting method best time Average time worst time worst-case secondary space Stability

Direct Insert sort o (n) o (n^2) o (n^2) O (1) Stability

Hill sort O (nlbn) o (nlbn) o (nlbn) O (1) Not stable

Direct Select sort O (n^2) o (n^2) o (n^2) O (1) Not stable

Heap sort O (nlbn) o (nlbn) o (nlbn) O (1) Not stable

Bubble sort o (n) o (n^2) o (n^2) O (1) Stability

Quick sort O (nlbn) o (nlbn) o (n^2) o (n) Not stable

Merge sort O (nlbn) o (nlbn) o (nlbn) o (n) Stability

Cardinal sort O (MN) O (MN) O (MN) O (n) Stability

Performance comparison of various sorting algorithms

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.