Java插入排序
下面我们创建一个java程序,实现使用插入排序对数组元素进行排序。 插入排序对于小元素是有好处的,因为排序大量元素它需要更多的时间。
让我们来看看一个简单的java程序,使用插入排序算法对数组进行排序。
public class InsertionSortExample {
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j - 1;
while ((i > -1) && (array[i] > key)) {
array[i + 1] = array[i];
i--;
}
array[i + 1] = key;
}
}
public static void main(String a[]) {
int[] arr1 = { 9, 14, 3, 2, 43, 11, 58, 22 };
System.out.println("Before Insertion Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();
insertionSort(arr1);// sorting array using insertion sort
System.out.println("After Insertion Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
}
}
执行上面代码,输出结果如下:
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
//更多请阅读:https://www.yiibai.com/java/insertion-sort-in-java.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)