-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertionSort.java
51 lines (44 loc) · 941 Bytes
/
InsertionSort.java
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
package OCJP;
class InsertionSortAlgo{
private long arr[];
private int numElements;
public InsertionSortAlgo(int value){
arr = new long[value];
numElements=0;
}
public void insert(int val){
arr[numElements] = val;
numElements++;
}
public void display(){
for(int i = 0;i<numElements;i++){
System.out.print(arr[i]+" ");
}
System.out.println();
}
public void insertionsort(){
int i,j;
for(j=1;j<numElements;j++){
long temp = arr[j];
i = j;
while(i>0 && arr[i-1]>=temp){
arr[i] = arr[i-1];
--i;
}
arr[i]= temp;
}
}
}
public class InsertionSort {
public static void main(String[] args) {
InsertionSortAlgo arr = new InsertionSortAlgo(10);
arr.insert(10);
arr.insert(2);
arr.insert(5);
System.out.println("Before Sorting:---------------------");
arr.display();
arr.insertionsort();
System.out.println("After Sorting:---------------------");
arr.display();
}
}