Insertion Sort(插入排序)
来源:互联网 发布:淘宝实木家具骗局真缘 编辑:程序博客网 时间:2024/06/07 18:05
基本思路:
当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。即逐个与左边元素进行比较。
import java.util.Scanner;public class Insertion { public static void sort(Comparable[] a)//排序,依次与前面有序的串比较,若小于则向前移动,直到前面有序为止。 { for(int i=1;i<a.length;i++) { for(int j=i;j>0;j--) { if(less(a[j],a[j-1])) { exch(a,j,j-1); } } } } private static void exch(Comparable[] a, int x, int y) {//交换 Comparable temp = a[x]; a[x] = a[y]; a[y] = temp; } private static boolean less(Comparable x, Comparable y) {//比较大小 return x.compareTo(y) < 0; } public static void main(String[] args) { Scanner cin = new Scanner(System.in); int N = cin.nextInt(); Integer[] array = new Integer[N]; for(int i=0;i<array.length;i++) { array[i] = cin.nextInt(); } sort(array); for(int i=0;i<array.length;i++) { System.out.print(array[i]+" "); } }}
时间复杂度分析
当倒置的数量很少时,插入排序很快。设想,当数组本身有序时,那么每个数只要和它左边的数进行比较就可,总共需要n-1次。
当数组是降序排列的并且不存在重复值,每个元素都移动到数组开头,那么需要进行1/2N^2次比较和1/2N^2次交换。
总结
当大多数有序的情况下使用插入排序更加迅速。
0 0
- 插入排序(insertion sort)
- insertion sort 插入排序
- 插入排序(Insertion Sort)
- 插入排序 Insertion Sort
- 插入排序Insertion sort
- 插入排序 (Insertion Sort)
- 插入排序Insertion sort
- 插入排序 Insertion Sort
- 插入排序 insertion sort
- 插入排序 insertion sort
- 插入排序Insertion sort
- 插入排序 Insertion sort
- 插入排序 Insertion Sort
- 插入排序-----Insertion Sort
- INSERTION-SORT插入排序
- 插入排序Insertion Sort
- insertion sort(插入排序)
- 插入排序-Insertion sort
- Java
- Memcache Java 客户端使用
- CUDA学习日记9
- 算法3.12 使用分治法的序列对准
- Hive Beeline HiveServer2使用
- Insertion Sort(插入排序)
- 栈的定义及应用场景
- 优化tableView性能—针对滑动时出现卡的现象
- testng 和 junit 的区别
- pycharm中将图片转化成字符画
- 自定义View——可拖动设置时间的时钟具体实现1
- 设计模式学习--访问者模式
- J-LINK the connected emulator is a j-link clone问题----自己增加了备注
- 李白喝酒