-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSorting.java
More file actions
33 lines (28 loc) · 1.46 KB
/
Copy pathInsertionSorting.java
File metadata and controls
33 lines (28 loc) · 1.46 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
package Sorting;
import java.util.Arrays;
public class InsertionSorting {
public static void main(String[] args) {
int[] arr = {3,4,2,1,5};
insertionSorting(arr);
System.out.println(Arrays.toString(arr));
}
// Insertion Sorting technique for sorting array
public static void insertionSorting(int[] arr){
for (int i = 0; i < arr.length-1; i++) { // (i will run till length-2)
// j is starting after ith position, moving backwards by comparing and replacing them. if it is bigger value then it breaks because previous elements are already sorted by it (it has started from the beginning and already checked it) i.e., started from comparing zero at the very beginning.
for (int j = i+1; j >0; j--) { // j will run till 0th index i.e., j>0 will be comapred with j at 0th index at the last
if (arr[j] < arr[j-1]) {
swap(arr, j , j-1);
}else{ // You can debug and check for this part.
break; // If previous elements are already sorted then no need to check for them because we are already checking them from beginning. Therefore, we are using break here
}
}
}
}
// Normal swap function for swapping lower values to previous positions.
public static void swap(int[] arr, int first, int second){
int temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}