Skip to content

Commit 838ae7f

Browse files
Update lessons/insertion.md
Co-authored-by: Utkarsh Mishra <76392681+Utkarsh1504@users.noreply.github.com>
1 parent 9f90c2b commit 838ae7f

File tree

1 file changed

+15
-35
lines changed

1 file changed

+15
-35
lines changed

lessons/insertion.md

Lines changed: 15 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -72,46 +72,26 @@ The worst case for insertion sort will occur when the input list is in decreasin
7272
```java
7373

7474
// Java program for implementation of Insertion Sort
75-
class InsertionSort {
76-
/*Function to sort array using insertion sort*/
77-
void insSort(int arr[])
78-
{
79-
int n = arr.length;
80-
for (int i = 1; i < n; ++i) {
81-
int key = arr[i];
75+
public class InsertionSort {
76+
public static void insertionSort(int[] input) {
77+
for (int i = 1; i < input.length; i++) {
8278
int j = i - 1;
83-
84-
/* Move elements of arr[0..i-1], that are
85-
greater than key, to one position ahead
86-
of their current position */
87-
while (j >= 0 && arr[j] > key) {
88-
arr[j + 1] = arr[j];
89-
j = j - 1;
79+
int temp = input[i];
80+
for (; j >= 0 && input[j] > temp; j--) {
81+
input[j + 1] = input[j];
9082
}
91-
arr[j + 1] = key;
83+
input[j + 1] = temp;
9284
}
9385
}
94-
95-
/* A utility function to print array of size n*/
96-
static void printArray(int arr[])
97-
{
98-
int n = arr.length;
99-
for (int i = 0; i < n; ++i)
100-
System.out.print(arr[i] + " ");
101-
102-
System.out.println();
103-
}
104-
105-
public static void main(String args[])
106-
{
107-
int arr[] = { 1,5,4,2,3 };
108-
109-
InsertionSort ob = new InsertionSort();
110-
ob.insSort(arr);
111-
112-
printArray(arr);
86+
87+
public static void main(String[] args) {
88+
int[] input = { 1, 5, 4, 2, 3 };
89+
insertionSort(input);
90+
for (int j : input) {
91+
System.out.print(j + " ");
92+
}
11393
}
114-
} /* This code is contributed by Abhijit Mishra. */
94+
}
11595
```
11696

11797
>

0 commit comments

Comments
 (0)