-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #6985 from Raghav-Bajaj/patch-1
Create InsertionSorting.java
- Loading branch information
Showing
1 changed file
with
29 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,29 @@ | ||
public class InsertionSort { | ||
public static void insertionSort(int[] arr) { | ||
int n = arr.length; | ||
for (int i = 1; i < n; i++) { | ||
int key = arr[i]; | ||
int j = i - 1; | ||
|
||
while (j >= 0 && arr[j] > key) { | ||
arr[j + 1] = arr[j]; | ||
j--; | ||
} | ||
arr[j + 1] = key; | ||
} | ||
} | ||
public static void printArray(int[] ar) { | ||
for (int number : ar) { | ||
System.out.print(number + " "); | ||
} | ||
System.out.println(); | ||
} | ||
public static void main(String[] args) { | ||
int[] arr = {19,20,22,17,99,20,3,69,2}; | ||
System.out.println("Original array :"); | ||
printArray(arr); | ||
insertionSort(arr); | ||
System.out.println("\nSorted array :"); | ||
printArray(arr); | ||
} | ||
} |