Java数据结构及算法实例:插入排序 Insertion Sort
时间:2021-02-19 15:21:00|栏目:JAVA代码|点击: 次
/**
* 选择排序的思想:
* 每次循环前,数组左边都是部分有序的序列,
* 然后选择右边待排元素,将其值保存下来
* 依次和左边已经排好的元素比较
* 如果小于左边的元素,就将左边的元素右移一位
* 直到和最左边的比较完成,或者待排元素不比左边元素小
*/
package al;
public class InsertionSort {
public static void main(String[] args) {
InsertionSort insertSort = new InsertionSort();
int[] elements = { 14, 77, 21, 9, 10, 50, 43, 14 };
// sort the array
insertSort.sort(elements);
// print the sorted array
for (int i = 0; i < elements.length; i++) {
System.out.print(elements[i]);
System.out.print(" ");
}
}
/**
* @author
* @param array 待排数组
*/
public void sort(int[] array) {
// min to save the minimum element for each round
int key; // save current element
for(int i=0; i<array.length; i++) {
int j = i; // current position
key = array[j];
// compare current element
while(j > 0 && array[j-1] > key) {
array[j] = array[j-1]; //shift it
j--;
}
array[j] = key;
}
}
}
上一篇:Spring中DAO被循环调用的时候数据不实时更新的解决方法
栏 目:JAVA代码
下一篇:Intellij IDEA下Spring Boot热切换配置
本文标题:Java数据结构及算法实例:插入排序 Insertion Sort
本文地址:http://www.codeinn.net/misctech/66124.html


阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机




