I was free today and trying to write small code for sorting algorithms. Below code is for the Insertion Sort. I think that it is very easy to understand and if you debug then you can see how algorithm works. I wish that it is helpful.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
package sorting; import java.util.Random; public class InsertionSort { public Random rdmNumber = new Random(); public int[] intArray = new int[10]; public static void main(String[] args) { InsertionSort object = new InsertionSort(); object.setRandomArray(object.intArray); System.out.println("Randomized Array:"); object.printArray(object.intArray); object.intArray = object.doInsertionSort(object.intArray); System.out.println("Sorted Array:"); object.printArray(object.intArray); } public int getRandomNumber(){ int intRandomNumber; intRandomNumber = rdmNumber.nextInt(100); return intRandomNumber; } public void setRandomArray(int[] array){ for(int i=0; i < array.length; i++){ array[i] = getRandomNumber(); } } public int[] doInsertionSort(int[] array){ for(int i=0; i < array.length; i++){ int intTemp = array[i]; int j = i -1; while(j >= 0 && array[j] > intTemp){ array[j + 1] = array[j]; j = j - 1; } array[j+1] = intTemp; } return array; } public void printArray(int[] array){ for(int i=0; i < array.length; i++){ System.out.print(array[i] + ", "); } System.out.println("\n"); } } |
Download File: InsertionSort
Read more at http://en.wikipedia.org/wiki/Insertion_sort