The Java implementation inserts the sort instance

  • 2020-04-01 03:43:10
  • OfStack

This article illustrates a Java method for implementing insertion sort. Share with you for your reference. The specific implementation method is as follows:


import java.util.Arrays; 
 
public class insertionSorting { 
  public static void main(String[] args) { 
    //Defines an integer array
    int[] nums = new int[]{4,3,-1,9,2,1,8,0,6}; 
    //Print an unsorted array
    System.out.println(" There is no previous result for sorting :" + Arrays.toString(nums)); 
    for(int index=0; index<nums.length; index++) { 
      //Gets the value to be inserted
      int key = nums[index]; 
      //Gets the lower value
      int position = index; 
      //The loop compares the previously sorted data and finds the appropriate place to insert it
      while(position >0 && nums[position-1] > key) { 
        nums[position] = nums[position-1]; 
        position--; 
      } 
      nums[position] = key; 
    } 
    //Print the sorted results
    System.out.println(" Sorted results :" + Arrays.toString(nums)); 
  } 
}

I hope this article has been helpful to your Java programming.


Related articles: