Created
July 25, 2022 12:31
-
-
Save connor-davis/a81882f102a8ca07d2d4a6ee91c4bb21 to your computer and use it in GitHub Desktop.
Java Insertion Sort Algorithm
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
/** | |
* This method will use the insertion sort algorithm to sort an int[] of | |
* numbers. | |
* | |
* @param numbers | |
* | |
* @return int[] | |
*/ | |
public static int[] insertionSort(int[] numbers) { | |
int n = numbers.length; | |
for (int i = 0; i < n; i++) { | |
int el = numbers[i]; | |
int x = i - 1; | |
while (x >= 0 && numbers[x] > el) { | |
numbers[x + 1] = numbers[x]; | |
x = x - 1; | |
} | |
numbers[x + 1] = el; | |
} | |
return numbers; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment