-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion_Sort.java
More file actions
44 lines (32 loc) · 1.05 KB
/
Insertion_Sort.java
File metadata and controls
44 lines (32 loc) · 1.05 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
34
35
36
37
38
39
40
41
42
43
44
import java.util.Arrays;
public class Insertion_Sort {
static void sort(int [] arr){
for (int i = 0; i < arr.length-1; i++) {
for (int j = i+1; j >0; j--) {
if (arr[j]<arr[j-1]) {
swap(arr, j-1, j);
}
else break;
}
}
}
// --------regular print method--------
// static void printArray(int [] arr){
// for (int i = 0; i < arr.length; i++) {
// System.out.print(arr[i]+" ");
// }
// System.out.println(" ");
// }
static void swap(int arr[], int first, int last){
int temp = arr[first];
arr[first] = arr[last];
arr[last] = temp;
}
public static void main(String[] args) {
int [] arr={5,2,3,7,-3,4,9,8,-6,1};
System.out.println("Before sorting the array is : "+ Arrays.toString(arr));
// printArray(arr);
sort(arr);
System.out.println("After sorting the array is : "+ Arrays.toString(arr));
}
}