-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertionsort.java
More file actions
32 lines (28 loc) · 977 Bytes
/
Copy pathinsertionsort.java
File metadata and controls
32 lines (28 loc) · 977 Bytes
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
import java.util.Arrays;
public class insertionsort {
// Corrected printArray method
public static void printArray(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[] = {8, 5, 6, 7, 3, 2, 9};
insertionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr));
}
// Corrected insertion sort method
static void insertionSort(int arr[]){
for(int i = 1; i < arr.length; i++){ // Start from 1 instead of 0
int current = arr[i];
int j = i - 1;
while (j >= 0 && current < arr[j]) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = current;
}
printArray(arr); // You can remove this if you don't want to print each step
}
}