简单排序--插入排序

来源:互联网 发布:缺德的医生 知乎 编辑:程序博客网 时间:2024/05/22 09:05

插入排序:

public void sort(){int in,out,temp;for(out=1;out<nElements;out++){temp = arr[out];in = out;while(in>0&&arr[in-1]>=temp){arr[in] = arr[in-1];//待插入的数据比其之前的数字大的右移,从小到大排序--in;//依次左移}arr[in] = temp;//直到遇到比temp小的,将temp插入}}

大多数情况下,插入排序是简单排序中最好的一种,时间复杂度仍为O(N^2),但在一般情况下比冒泡快一倍,比选择还要快一些。

先将下标为1的数组元素放入temp,从移走的元素(放到temp)处,向左比较:


将下标为1的数组元素放入temp:


从空处向左比较,为temp找合适的插入点:


outer右移,指向下一个待插入的元素,将其放入temp:


排序完成:


完整代码:

package TwoArray;/** * 插入排序   将待排序的一个一个放入temp,与所处位置之前的数值比较,一个个插入 * 将数组下标1的值作为分界点,暂存在临时变量temp,temp依次与左边的比较若左边in的比其大,将左边比其大的依次右移,直到遇到比其小的腾出一个空位 * 插入这个空位,in一直指向空位位置,out一直右移指向下一个待插入的元素。大多数情况下,插入排序是简单排序中最好的一种,时间复杂度O(N^2) * @author zhic * */public class InsertionSort {int[] arr;int nElements;public InsertionSort(int max){arr = new int[max];nElements = 0;}public void insert(int value){arr[nElements] = value;nElements++;}public void display(){for(int i=0;i<nElements;i++){System.out.print(arr[i] + " ");}}public void swap(int one,int two){int temp = arr[one];arr[one] = arr[two];arr[two] = temp;}public void sort(){int in,out,temp;for(out=1;out<nElements;out++){temp = arr[out];in = out;while(in>0&&arr[in-1]>=temp){arr[in] = arr[in-1];//待插入的数据比其之前的数字大的右移,从小到大排序--in;//依次左移}arr[in] = temp;//直到遇到比temp小的,将temp插入}}public static void main(String[] args){InsertionSort arr = new InsertionSort(15);arr.insert(10);arr.insert(40);arr.insert(0);arr.insert(20);arr.insert(2);arr.insert(1);arr.insert(5);arr.insert(14);arr.insert(70);arr.insert(11);arr.display();System.out.println();arr.sort();arr.display();}}


0 0
原创粉丝点击