-
Notifications
You must be signed in to change notification settings - Fork 41
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
dc2039a
commit 9e3290a
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} | ||
} |