Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /**
- * Problem 1: Insertion Sort
- *
- * Prompt: Given an unsorted array of integers, return the array sorted
- * using insertion sort.
- *
- * Input: input {Array}
- * Output: {Array}
- *
- * Example: [3,9,1,4,7] --> [1,3,4,7,9]
- *
- */
- import java.util.*;
- class BasicSort {
- public static void main(String[] args){
- int[] nums = {1000, 2, 12 , 134, 54, 677};
- System.out.println(Arrays.toString(insertion(nums)));
- }
- public static int[] insertion(int[] input) {
- int temp, lastSorted, index;
- for(lastSorted = 1; lastSorted < input.length; lastSorted++){
- index = lastSorted;
- while(index > 0 && input[index-1] > input[index]){
- temp = input[index];
- input[index] = input[index-1];
- input[index-1] = temp;
- //repeat the comparison until index reaches the element that
- //is smaller than it
- index = index -1;
- }
- }
- return input;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment