gelita

Insertion sort

Feb 18th, 2020
366
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5 1.12 KB | None | 0 0
  1. /**
  2.   *  Problem 1: Insertion Sort
  3.  *
  4.  *  Prompt:    Given an unsorted array of integers, return the array sorted
  5.  *             using insertion sort.
  6.  *
  7.  *  Input:     input {Array}
  8.  *  Output:    {Array}
  9.  *
  10.  *  Example:   [3,9,1,4,7] --> [1,3,4,7,9]
  11.  *
  12.  */
  13.  
  14. import java.util.*;
  15.  
  16. class BasicSort {
  17.  
  18.     public static void main(String[] args){
  19.         int[] nums =  {1000, 2, 12 , 134, 54, 677};
  20.         System.out.println(Arrays.toString(insertion(nums)));
  21.     }
  22.  
  23.     public static int[] insertion(int[] input) {
  24.         int temp, lastSorted, index;
  25.             for(lastSorted = 1; lastSorted < input.length; lastSorted++){
  26.                 index = lastSorted;
  27.                 while(index > 0 && input[index-1] > input[index]){
  28.                         temp = input[index];
  29.                         input[index] = input[index-1];
  30.                         input[index-1] = temp;  
  31.                         //repeat the comparison until index reaches the element that
  32.                         //is smaller than it
  33.                         index = index -1;
  34.                 }
  35.             }
  36.     return input;
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment