Advertisement
16120

Insertion sort

May 8th, 2019
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.57 KB | None | 0 0
  1. import java.util.Arrays;
  2.  
  3. public class insertion {
  4.  
  5.     public static void insertionSort(int[] arr) {
  6.         for (int i = 1; i < arr.length; i++) {
  7.             int next = arr[i];
  8.             int j = i;
  9.             while (j > 0 && arr[j - 1] > next) {
  10.                 arr[j] = arr[j - 1];
  11.                 j--;
  12.             }
  13.             arr[j] = next;
  14.         }
  15.     }
  16.  
  17.     static void print(int arr[], int n) {
  18.         for (int i = 0; i < n; i++)
  19.             System.out.print(arr[i] + " ");
  20.     }
  21.    
  22.     public static void main(String[] args) {
  23.         int[] numbers = { 10, 45, 65, 11, 23, 7 };
  24.         int n = numbers.length;
  25.         insertionSort(numbers);
  26.         print(numbers, n);
  27.     }
  28.  
  29. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement