Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 8 additions & 8 deletions code/sorting/src/insertion_sort/insertion_sort.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
// Part of Cosmos by OpenGenus Foundation
class InsertionSort {
void sort(int arr[]) {
class InsertionSort {
void sort(int arr[]) { // sort() performs the insertion sort on the array which is passed as argument from main()
for (int i = 0; i < arr.length; ++i) {
for (int j = i; j > 0 && arr[j - 1] > arr[j]; j--) {
for (int j = i; j > 0 && arr[j - 1] > arr[j]; j--) { // swapping of elements if j-1th element is greater than jth element
int temp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = temp;
Expand All @@ -12,10 +12,10 @@ void sort(int arr[]) {

// Driver method
public static void main(String args[]) {
int arr[] = {8, 2, 111, 3, 15, 61, 17};
System.out.println("Before: " + Arrays.toString(arr));
InsertionSort ob = new InsertionSort();
ob.sort(arr);
System.out.println("After:" + Arrays.toString(arr));
int arr[] = {8, 2, 111, 3, 15, 61, 17}; // array to be sorted
System.out.println("Before: " + Arrays.toString(arr)); // printing array before sorting
InsertionSort ob = new InsertionSort(); // object of class InsertionSort is created
ob.sort(arr); // arr is passed as argument to the function sort() is called
System.out.println("After:" + Arrays.toString(arr)); // printing array after insertion sort is applied
}
}