-
Notifications
You must be signed in to change notification settings - Fork 4
/
InsertionSort.java
42 lines (38 loc) · 955 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
import java.util.Arrays;
import java.util.Scanner;
public class InsertionSort {
public static void main(String[] args) {
int A[] = new int[10];
populateArray(A);
System.out.println("Before Sorting: ");
printArray(A);
// sort the array
insertionSort(A);
System.out.println("\nAfter Sorting: ");
printArray(A);
}
/**
* This method will sort the integer array using insertion sort in java algorithm
*
* @param arr
*/
private static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int valueToSort = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > valueToSort) {
arr[j] = arr[j - 1];
j--;
}
arr[j] = valueToSort;
}
}
public static void printArray(int[] B) {
System.out.println(Arrays.toString(B));
}
public static void populateArray(int[] B) {
for (int i = 0; i < B.length; i++) {
B[i] = (int) (Math.random() * 100);
}
}
}