首页 > 学院 > 开发设计 > 正文

【排序算法】之插入排序

2019-11-08 02:58:28
字体:
来源:转载
供稿:网友

基本思想:每步将一个待排序的记录,按其顺序码大小插入到前面已经排序的字序列的合适位置(从后向前找到合适位置后),直到全部插入排序完为止。


实例:

这里写图片描述


算法实现:

public class InsertionSort { public static void main(String[] args) { System.out.PRintln("Hello World!"); int[] numbers = {57, 68, 59, 52}; insertSort(numbers); } public static void insertSort(int[] numbers){ int size = numbers.length; int temp = 0; int j = 0; for(int i=0; i<size; i++ ){ temp = numbers[i]; //假如temp比前面的值小, 则将前面的值后移 for(j = i; j>0 && temp < numbers[j-1]; j--){ numbers[j] = numbers[j-1]; } numbers[j] = temp; } System.out.println("排序后:"); for (int num : numbers) System.out.print(num + "/t"); }}Terminal输出:Hello World!52 57 59 68

效率:

时间复杂度:O(n^2).


上一篇:476. Number Complement

下一篇:PAT 1019

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表