An example of insertion sort from the beginning of the JAVA algorithm

  • 2020-04-01 02:52:43
  • OfStack

During this period of time, I will read the introduction to algorithm this book, feel a lot of benefits. Here also according to the algorithm involved in the introduction to the algorithm is implemented in Java.
In the first one we started with sorting, and the principle of insertion sort is very simple, just like when we play poker. If the card in his hand is smaller than the card in front of him, he will continue to compare, knowing that this card is smaller than the card in front of him and can be inserted in his back. Of course, in the computer, we also need to move the CARDS back by one place.
I'm going to give you the algorithm directly here, and I'm sure many programmers feel that some programs are better than our natural language.


public class Sort {
 public void sort(int[] s){
  if(s.length<1){
   return ;
  }
  for (int i = 1; i < s.length; i++) {
   int key =s[i];
   int j=i-1;
   while(j>=0&&s[j]>key){
    s[j+1]=s[j];
    j--;
   }
   s[j+1]=key;
  }
 }
 public static void main(String[] args) {
  Sort s=new Sort();
  int[] st =new int[]{7,5,3,4,2,1};
  s.sort(st);
  for (int i = 0; i < st.length; i++) {
   System.out.println(st[i]);
  }
 }
}

Its time complexity is o (n*n), is the original address (any time you need a constant second element space to store data and merge sort is not the original address)


Related articles: