Eight sorting algorithms

Source: Internet
Author: User

Directory

    • Sorting algorithms
      • A sorting algorithm with time complexity O (n^2)
        • 1.1 Bubble sort (bubblesort)
        • 1.2 Select sort (selectionsort)
        • 1.3 Insert Sort (insertionsort)
      • Second, the time complexity is O (log (n)) sorting algorithm
        • 2.1 Merge sort (mergesort)
        • 2.2 Quick Sort (quickSort)
        • 2.3 Heap Sorting
        • 2.4 Hill Sort (shellsort)
      • Three, bucket sequencing (time complexity O (n))
        • 3.1 Counting sort
        • 3.2 Cardinality Sorting
Sorting algorithms

Comparison between sorting algorithms:

Sorting Algorithms worst-time analysis Average Time complexity Degree of stability Complexity of Space
Bubble sort O (n^2) O (n^2) Stability O (1)
Select sort O (n^2) O (n^2) Not stable O (1)
Insert Sort O (n^2) O (n^2) Stability O (1)
Merge sort O (NLOGN) O (NLOGN) Stability O (N)
Quick Sort O (n^2) O (NLOGN) Not stable O (1)
Heap Sort O (n^2) O (N*LOGN) Not stable O (1)
Hill sort O (n^2) O (n^1.3) Not stable O (1)
Bucket sort O (N) O (N) Stability O (N)
One, Time complexity O (n^2) sorting algorithm 1.1 bubble sort (bubblesort)
    • The n-1 wheel is sorted, and the elements in the sorted array of each round are exchanged 22 in turn to obtain the largest element;
    • Time complexity O (n^2), Spatial complexity O (1);
public class BubbleSort {    public int[] bubbleSort(int[] A) {        // write code here        if(A == null || A.length < 2) return A;        for(int i = 0; i < A.length - 1; i++){            for(int j = 0; j < A.length - i - 1; j++){                if(A[j] > A[j+1]){                    swap(A, j, j+1);                }            }        }        return A;    }        public void swap(int[] A, int i1, int i2){        int tmp = A[i1];        A[i1] = A[i2];        A[i2] = tmp;    }}
1.2 Select sort (selectionsort)
    • N-1 wheel Exchange, each round of exchange to get the smallest element
    • Time complexity O (n^2), Spatial complexity O (1);
public class SelectionSort {    public int[] selectionSort(int[] A) {        // write code here        if(A == null || A.length < 2) return A;        for(int i = 0; i < A.length - 1; i++){            for(int j = i + 1; j < A.length; j ++){                if(A[i] > A[j]){                    swap(A, i, j);                }            }        }        return A;    }     public void swap(int[] A, int i1, int i2){        int tmp = A[i1];        A[i1] = A[i2];        A[i2] = tmp;    }}
1.3 Insert Sort (insertionsort)
    • Time complexity O (n^2), Spatial complexity O (1);
    • When the array elements are ordered, the time complexity O (n)
public class InsertionSort {    public int[] insertionSort(int[] A, int n) {        // write code here        for(int i = 1; i < A.length; i++){            int key = A[i];            int pre = i - 1;            while(pre >= 0 && A[pre] > key){                A[pre+1] = A[pre--];            }            A[pre + 1] = key;        }        return A;    }}
Second, the time complexity of O (log (n)) sorting algorithm 2.1 merge sort (mergesort)
    • Time Complexity O (log (n)), Spatial complexity O (n)
    • The time complexity of the merge sort is independent of the order of the ordered array elements;
public class MergeSort {public int[] mergesort (int[] A, int n) {//write code here if (A = = NULL | |        A.length < 2) return A;        int[] tmp = new Int[a.length];        Divide (A, 0, A.LENGTH-1, TMP);    return A; }//array merge public void merge (int[] A, int. left, int. right, int mid, int[] tmp) {for (int i = left; I <= righ T        i++) {Tmp[i] = A[i];        } int L1 = left, L2 = mid+1, and index = left;            for (int i = left, I <= right; i++) {if (L1 > mid) {a[index++] = tmp[l2++];            }else if (L2 > right) {a[index++] = tmp[l1++];            }else if (TMP[L1] < TMP[L2]) {a[index++] = tmp[l1++];            }else{a[index++] = tmp[l2++];            }}} public void Divide (int[] A, int. left, int. right, int[] tmp) {if (left < right) { Can prevent left+right out of int range int MID = left + when compared to Mid = (left + right)/2(Right-left)/2;            Divide (A, left, Mid, TMP);            Divide (A, mid+1, right, TMP);        Merge (A, left, right, Mid, TMP); }    }}
2.2 Quick Sort (quickSort)

optimal Condition: The elements are evenly distributed and can be taken to the middle position each time.

    • Time Complexity O (log (n)), Spatial complexity O (LOGN);

worst case: time complexity O (n^2), Space complexity O (n), the following three worst cases

    • The array is already ordered in a positive order (same order).
    • The array is already sorted in reverse order.
    • All elements are the same (1, 2 special cases)
public class QuickSort {    public int[] quickSort(int[] A, int n) {        // write code here        quick(A, 0, A.length - 1);        return A;    }        public void quick(int[] A, int left, int right){        if(left >= right) return ;        int key = A[left];        int head = left, tail = right+1;        while(true){            while(A[++head] <= key) if(head == right) break;            while(A[--tail] > key) if(tail == left) break;            if(head >= tail) break;            int tmp = A[head];            A[head] = A[tail];            A[tail] = tmp;        }        A[left] = A[tail];        A[tail] = key;        quick(A, left, tail-1);        quick(A, tail + 1,right);    }}
2.3 Heap Sorting
    • Time Complexity O (Nlog (n)), Spatial complexity O (1)

    • Worst case, the array element is already small to large ordered, time complexity O (n^2)

public class HeapSort {    public int[] heapSort(int[] A, int n) {        // 建堆        for(int i = A.length/2; i >= 0; i--){            heapAdjust(A, i, A.length);        }        for(int i = A.length - 1; i >= 0; i--){            int head = A[0];            A[0] = A[i];            A[i] = head;            heapAdjust(A, 0, i);        }        return A;    }    // 堆调整 O(log(n))    public void heapAdjust(int[] A, int parent, int len){        int head = A[parent];        while(parent*2+1 < len){            int childLeft = parent*2 + 1;            if(childLeft + 1 < len && A[childLeft + 1] > A[childLeft]){                childLeft++;            }            if(A[childLeft] < head) break;            A[parent] = A[childLeft];            parent = childLeft;        }        A[parent] = head;    }}
2.4 Hill Sort (shellsort)
    • Shell sorting is much slower than quicksort,mergesort,heapsort. Suitable for situations where the volume of data is less than 5000 and speed is not particularly important. It is very good to repeat the sequence of numbers with a smaller amount of data.

    • Time Complexity O (Nlog (n)), Spatial complexity O (1)
public class ShellSort {    public int[] shellSort(int[] A, int n) {        for(int i = n; i >= 1; i /= 2){            for(int j = i; j < n; j++){                int key = A[j];                int pre = j - i;                while(pre >= 0 && A[pre] > key){                    A[pre + i] = A[pre];                    pre -= i;                }                A[pre + i] = key;            }        }        return A;    }}
Three, bucket sequencing (time complexity O (n)) 3.1 count sort
    • The counting sort applies to the array of elements within a certain finite range;
    • Time complexity O (n), spatial complexity O (m)
import java.util.*;public class CountingSort {    public int[] countingSort(int[] A, int n) {        if(A == null || A.length < 2) return A;        int min = A[0], max = A[0];        for(int i = 0; i < A.length; i++){            min = Math.min(min, A[i]);            max = Math.max(max, A[i]);        }        int[] bucket = new int[max - min + 1];        // 入桶        for(int i = 0; i < A.length; i++){            bucket[A[i] - min]++;        }        // 出桶        int index = 0;        for(int i = 0; i < bucket.length; i++){            while(bucket[i]-- > 0){                A[index++] = i + min;            }        }        return A;    }}
3.2 Cardinality Sorting
    • Time complexity O (n), spatial complexity O (n)
// 保证元素均小于等于2000的基数排序public class RadixSort {    public int[] radixSort(int[] A, int n) {        if(A == null || n < 2) return A;        int[][] bucket = new int[10][n]; // 创建10个桶,每个桶需要的长度都有可能为n        int[] count = new int[10];  // 记录每个对应桶中装入的元素个数                for(int i = 1; i <= 1000; i *= 10) {            for(int k = 0; k < n; k++) {                int num = A[k] / i % 10; // 获取位数上对应数字                bucket[num][count[num]++] = A[k];            }            // 从bucket中将数据倒回A中            int index = 0;            for(int k = 0; k < 10; k++) {                for(int j = 0; j < count[k]; j++) {                    A[index++] = bucket[k][j];                }                count[k] = 0; // 重置为0            }        }        return A;    }}

Eight 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.