Last active
August 29, 2015 14:14
-
-
Save arjunrao87/92c14389e6f4d8e6fc24 to your computer and use it in GitHub Desktop.
Insertion sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package sort; | |
| import java.util.Arrays; | |
| public class InsertionSort { | |
| public static void main( String[] args ){ | |
| InsertionSort sort = new InsertionSort(); | |
| int[] arr = {5,4,3,1,2}; | |
| arr = sort.sort(arr); | |
| System.out.println( Arrays.toString(arr) ); | |
| } | |
| private int [] sort( int[] arr ){ | |
| int length = arr.length; | |
| int currPointer = 1; | |
| while( currPointer < length ){ | |
| int tempPointer = currPointer; | |
| for( int i = currPointer-1; i>=0; i -- ){ | |
| if( arr[tempPointer] < arr[i] ){ | |
| swap( arr, tempPointer, i ); | |
| tempPointer--; | |
| }else { | |
| break; | |
| } | |
| } | |
| currPointer++; | |
| } | |
| return arr; | |
| } | |
| private void swap(int[] arr, int currPointer, int i) { | |
| int t = arr[currPointer]; | |
| arr[currPointer] = arr[i]; | |
| arr[i] = t; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment