Insertion Sorting

Main Class

This class is used to call the insertion sorting logic to pass an integer array and array length

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package sortings;

public class Main {

	public static void main(String[] args) {
		
		int[] intAry = {10,30,20,70,40};
		
		displayAray(intAry);
		System.err.println();
		System.err.println("--------------------");
		InsertionSort obj = new InsertionSort();
		obj.insertionSort(intAry, 5);
		
		displayAray(intAry);
	}
	public static void displayAray(int[] intAry) {
		for (int i : intAry) {
			System.out.print(i);
		}		
	}

}	
Insertion Sorting Logic
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
package sortings;

public class InsertionSort {

	public int[] insertionSort(int[] intAry, int size) {
		int j = 0;
		for (int i = 1; i < intAry.length; i++) {
			j = i;
			while (j > 0 && intAry[j] < intAry[j - 1]) {
				swap(j, j - 1, intAry);
				j = j - 1;
			}
		}
		return intAry;
	}

	private void swap(int i, int j, int[] intAry) {
		int temp = 0;
		temp = intAry[i];
		intAry[i] = intAry[j];
		intAry[j] = temp;
	}

}

Comments