-
Notifications
You must be signed in to change notification settings - Fork 14
/
InsertionSort.java
47 lines (41 loc) · 1.22 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
37
38
39
40
41
42
43
44
45
46
47
import java.util.*;
//Problem : Insertion Sort
public class InsertionSort {
public static void insertionSort(int arr[]) {
for(int i=1; i<arr.length; i++) {
int curr = arr[i];
int prev = i-1;
//to find the index where curr is to be inserted
while(prev >= 0 && arr[prev] > curr) {
arr[prev+1] = arr[prev];
prev--;
}
arr[prev+1] = curr;
}
}
public static void insertionSortDescending(int arr[]) {
for(int i=1; i<arr.length; i++) {
int curr = arr[i];
int prev = i-1;
//to find the index where curr is to be inserted
while(prev >= 0 && arr[prev] < curr) {
arr[prev+1] = arr[prev];
prev--;
}
arr[prev+1] = curr;
}
}
public static void printArr(int arr[]) {
for(int i=0; i<arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String args[]) {
int arr[] = {5, 4, 1, 3, 2};
insertionSortDescending(arr);
printArr(arr);
//Inbuilt Sorting Algo
//Arrays.sort(arr);
}
}