直接插入算法学习使用代码如下
import untils.AlgorithmUtils;
import java.util.Arrays;
public class Insert {
public static int[] stduyInsertSort(int[] arr) {
System.out.println("数组长度为: " + arr.length);
System.out.println("传入的原数组为: " + Arrays.toString(arr));
System.out.println("开始排序-----");
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
AlgorithmUtils.swap(arr, j, j - 1);
}
}
System.out.println("第 " + (i + 1) + " 次排序结果: " + Arrays.toString(arr));
}
return arr;
}
}
package untils;
public class AlgorithmUtils {
public static void swap(int[] arr, int a, int b) {
int temp = arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
}
直接插入算法作为工具类使用代码如下
public class Insert {
public static int[] insertSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j > 0; j--) {
if (arr[j] < arr[j - 1]) {
AlgorithmUtils.swap(arr, j, j - 1);
}
}
}
return arr;
}
}