Prompt
Write a function that takes in an array of integers and returns a sorted version of that array. Use the Insertion Sort algorithm to sort the array.
Sample Input
array = [8, 5, 2, 9, 5, 6, 3]
Sample Output
[2, 3, 5, 5, 6, 8, 9]
Solution
import java.util.*;
class Program {
// Best: O(n) time | O(1) space
// Average/Worst : O(n^2) time | O(1) space
public static int[] insertionSort(int[] array) {
// Write your code here.
for (int i = 1; i < array.length; i++) {
int j = i;
while (j > 0 && array [j - 1] > array[j]) {//A
swap(j, array);
j--;
}
}
return array;
}
public static void swap(int j, int[] array) {
int temp = array[j];
array[j] = array [j - 1];
array[j - 1] = temp;
}
}
# A
while的多条件循环