Sort ----- Insertion Sort (java)

One: What is Insertion Sort

    To make room for the element to be inserted, we need to shift all remaining elements to the right by one bit before inserting, all elements to the left of the current index are ordered, but the final position is indeterminate, in order to make room for the smallest element Out of space, elements may be moved at any time.

    

Two: the realization of sorting

public class InsertSort {
    public static void main(String args[]){
        int a[] = {10,23,5,2,112,34,22,99,0,45,1};
        sort(a);
        show(a);
    }

    private static void sort(int[] a) {
        for(int i=1;i<a.length;i++){
            for(int j=i;j>0 && less(a,j-1,j);j--){
                exchange(a,j,j-1);
            }
        }
    }

    private static void exchange(int[] a, int m, int n) {
        int temp = a[n];
        a[n] = a[m];
        a[m] = temp;
    }

    private static boolean less(int[] a, int m, int n) {
        if(a[m] >a[n]){
            return true;
        }
        return false;
    }

    private static void show(int[] a) {
        System.out.print("Sort result");
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+",");
        }
    }
}

Three: Summary

    Insertion sort is very efficient for partially sorted arrays, and it is also very suitable for small-scale arrays. Partially sorted means that the number of inversions in the array is less than a certain multiple of the array size. A typical partially sorted array is:

  1.     Each element in the array is not far from its final position.
  2.     An ordered large array followed by a small array.
  3.     The positions of only a few elements in the array are indeterminate.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325618919&siteId=291194637