Skip to content

Commit

Permalink
Create insertionSort.java
Browse files Browse the repository at this point in the history
  • Loading branch information
AbhijeetPatil2005 authored and x0lg0n committed Oct 30, 2024
1 parent dc2039a commit 9e3290a
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions Java/insertionSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
public class InsertionSort {
public static void insertionSort(int[] array) {
int n = array.length;
for (int i = 1; i < n; i++) {
int key = array[i];
int j = i - 1;

// Move elements of array[0..i-1], that are greater than key, to one position ahead of their current position
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = key;
}
}

public static void main(String[] args) {
int[] array = { 12, 11, 13, 5, 6 };

System.out.println("Original array:");
printArray(array);

insertionSort(array);

System.out.println("Sorted array:");
printArray(array);
}

public static void printArray(int[] array) {
for (int i : array) {
System.out.print(i + " ");
}
System.out.println();
}
}

0 comments on commit 9e3290a

Please sign in to comment.