1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| public class InsertSort { public static void main(String[] args) { int[] arr = {13, 3, 303, 105}; InsertSort(arr); }
public static void InsertSort(int[] arr) { int insertValue = 0; int inserIndex = 0;
for (int i = 1; i < arr.length; i++) { insertValue = arr[i]; inserIndex = i-1;
while (inserIndex >= 0 && insertValue < arr[inserIndex]) { arr[inserIndex+1] = arr[inserIndex]; inserIndex --; }
if (inserIndex+1 != i) { arr[inserIndex+1] = insertValue; }
System.out.println(Arrays.toString(arr)); } } }
|