Skip to content

Instantly share code, notes, and snippets.

@arjunrao87
Last active August 29, 2015 14:14
Show Gist options
  • Select an option

  • Save arjunrao87/92c14389e6f4d8e6fc24 to your computer and use it in GitHub Desktop.

Select an option

Save arjunrao87/92c14389e6f4d8e6fc24 to your computer and use it in GitHub Desktop.
Insertion sort
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