算法-插入排序

来源:互联网 发布:windows 8.1 10 whql 编辑:程序博客网 时间:2024/06/05 09:13

插入排序

插入排序算法是通过比较和插入来实现排序的。
思路:通过对未排序的数据执行逐个插入至合适的位置而完成排序工作。

排序流程

1首先对数组的前两个数据进行从小到大的排序。
2接着将第3个数据与排好序的两个数据进行比较,将第3个数据插入合适的位置。
3然后,将第4个数据插入已排好序的前3个数据中。
4不断重复上述过程,直到把最后一个数据插入合适的位置。最后,便完成了对原始数组从小到大的排序。
注:插入排序算法在对n个数据进行排序时,无论原数据有无顺序,都需要进行n-1步的中间排序。

代码

public class InsertSort {    public void sort(int[] data){        int current;        int temp;        for(int i=1;i<data.length;i++){            current=i-1;            temp=data[i];            while(current>=0&&data[current]>temp){                data[current+1]=data[current];                current--;            }            data[current+1]=temp;        }    }}
0 0