Insertion sort - direct insertion sort

Insertion sort is a simple and intuitive sorting algorithm. It works by constructing an ordered sequence. For unsorted data, scan from back to front in the sorted sequence, find the corresponding position and insert it. In the implementation of insertion sort, in the process of scanning from the back to the front, it is necessary to repeatedly move the sorted elements to the back step by step to provide the insertion space for the latest element.

  • Algorithm steps:

Initialize an array.

untitled.png

(1)   For the first element, because there is no comparison, it is directly regarded as an ordered sequence.

untitled.png


(2)  
Get the next element from the array, scan from back to front in the sorted element sequence, and make a judgment. If the element of the sorted sequence is greater than the new element, move the element to the next position. until the position where the sorted element is less than or equal to the new element is found.

(3)   Repeat this (2) step

untitled.png

  • Algorithm implementation:

public class InsertSort {

 

   public static void main(String[] args) {

      int arr []= {56,20,38,75,26,91,16};

      System.out.println("排序前:"+Arrays.toString(arr));

      sort(arr);

System.out.println ( " After sorting : " +       Arrays.toString ( arr ));

   }

   public static voidsort(intarr[]) {

      int temp,j;

      for(int i=1;i<arr.length;i++) {

         temp=arr[i];

         for(j=i-1;j>=0 && arr[j]>temp;j--) {

            arr[j+1]=arr[j];

         }

         arr[j+1]=temp;

      }

   }

}

Before sorting: [56, 20, 38, 75, 26, 91, 16]

After sorting: [16, 20, 26, 38, 56, 75, 91]


Guess you like

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