-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSort.java
37 lines (30 loc) · 1.18 KB
/
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
public class InsertionSort {
public int[] insertionSort(int[] array){
for (int j = 1; j< array.length;j++){//j= 1; //j=2
int key = array[j]; //key= "2" //key= "4"
int i = j-1;//i = 0 //i = 1
while ((i>=0) && (array[i]>=key)){ //(1>0) & (array[0] ==5 > 2 // & (array[1] ==5 > 4
array[i+1] = array[i]; //array[1] = array[0] ->5 is second place //array[2] = array[1] ->4 is second place, 5 is third place
i = i-1; //-1
}
array[i+1] = key;
}
return array;
}
public void reversedInsertionSort(int[] array){
for (int j = 1; j< array.length;j++){
int key = array[j];
int i = j-1;
while ((i>=0) && (array[i]<=key)){
array[i+1] = array[i];
i = i-1;
}
array[i+1] = key;
}
}
public void calculateExeTime(int[] array){
int sizeOfArray = array.length;
int insertionSortAlgo = sizeOfArray*sizeOfArray;
System.out.println("The Number of steps for ordering an array of "+sizeOfArray+" elements with insertion sort is: "+insertionSortAlgo);
}
}