-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.java
More file actions
47 lines (43 loc) · 1.04 KB
/
InsertionSort.java
File metadata and controls
47 lines (43 loc) · 1.04 KB
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
package algorithm.sorting;
/**
* The type Insertion sort.
*/
public class InsertionSort {
/**
* The Obj.
*/
static Helper obj = new Helper();
/**
* Sort int [ ].
*
* @param arr the arr
* @return the int [ ]
*/
public static int[] sort(int[] arr){
int arrSize=arr.length;
int ele, j;
//Traverse through 1 to size of the array
for (int i = 1; i < arrSize; i++) {
ele = arr[i]; // Element to be inserted
j = i - 1;
//shifts elements back to create space for the element to be inserted
while (j >= 0 && arr[j] > ele) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = ele;
}
return arr;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String[] args){
int arr[] = {5,4,1,0,5,95,4,-100,200,0};
obj.printArray(arr, arr.length);
sort(arr);
obj.printArray(arr, arr.length);
}
}