Java与算法之(9) - 直接插入排序
发布时间:2020-12-13 21:15:53 所属栏目:PHP教程 来源:网络整理
导读:直接插入排序是最简单的排序算法,也比较符合人的思惟习惯。想像1下玩扑克牌抓牌的进程。第1张抓到5,放在手里;第2张抓到3,习惯性的会把它放在5的前面;第3张抓到7,放在5的后面;第4张抓到4,那末我们会把它放在3和5的中间。 直接插入排序正是这类思路,
直接插入排序是最简单的排序算法,也比较符合人的思惟习惯。想像1下玩扑克牌抓牌的进程。第1张抓到5,放在手里;第2张抓到3,习惯性的会把它放在5的前面;第3张抓到7,放在5的后面;第4张抓到4,那末我们会把它放在3和5的中间。 直接插入排序正是这类思路,每次取1个数,从前向后找,找到适合的位置就插进去。 代码也非常简单: /**
* 直接插入排序法
* Created by autfish on 2016/9/18.
*/
public class InsertSort {
private int[] numbers;
public InsertSort(int[] numbers) {
this.numbers = numbers;
}
public void sort() {
int temp;
for(int i = 1; i < this.numbers.length; i++) {
temp = this.numbers[i]; //取出1个未排序的数
for(int j = i - 1; j >= 0 && temp < this.numbers[j]; j--) {
this.numbers[j + 1] = this.numbers[j];
this.numbers[j] = temp;
}
}
System.out.print("排序后: ");
for(int x = 0; x < numbers.length; x++) {
System.out.print(numbers[x] + " ");
}
}
public static void main(String[] args) {
int[] numbers = new int[] { 4,3,6,2,7,1,5 };
System.out.print("排序前: ");
for(int x = 0; x < numbers.length; x++) {
System.out.print(numbers[x] + " ");
}
System.out.println();
InsertSort is = new InsertSort(numbers);
is.sort();
}
} 测试结果:
排序前: 4 3 6 2 7 1 5
排序后: 1 2 3 4 5 6 7 直接插入排序的时间复杂度,最好情况是O(n),最坏是O(n^2),平均O(n^2)。(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |