zoukankan      html  css  js  c++  java
  • 原创 插入排序算法

    贴出源码:
    public class InsertSort {

    /**
    * @param source    需要插入的位置,是从索引0开始的
    * @param p
    * @param len
    */
    public static void insertSort(int []source,int p,int len){
    int start =0,end = source.length,position = p,midd = 0;
    int []sortSource ={0};
    while(source[position-1]<=source[position]){
    position++;
    if(position==len){
    printf(source);
    break;
    }
    }
    while(position<len){
    midd = judgeMidd(source,midd,position-1,source[position]);
    source = moveMidd(source,midd,position,source[position]);
    position++;
    }

    printf(source);
    }
    /**
    * @param source     数据源
    * @param start      start+1才是真正的移动位置
    * @param end        end位置是value的位置
    * @param value      移动的数值
    * @return
    */
    public static int[] moveMidd(int []source,int start,int end ,int value){
    if((end-start)==1){
    if(source[end]>source[start])
    ;
    else{
    int temp = source[end];
    source[end] = source[start];
    source[start] = temp;
    }
    return source;
    }
    while(end>start){
    source[end] = source[end-1];
    end--;
    }
    source[start+1] = value;

    return source;
    }

    /**
    * @param source  数据源
    * @param start   开始处
    * @param end     结束处
    * @param value   要插入的值
    * @return        value值该插入的位置
    *               
    */
    public static int judgeMidd(int []source,int start ,int end,int value){
    int midd = 0;
    if(source[end]<value)
    return end;
    for(;;){
    midd = (start+end)/2;
    //            if(midd == start) return midd;
    if(source[midd]<=value&&source[midd+1]>value)
    return midd;
    if(source[midd]>=value)
    end=midd;
    else start  = midd;
    }
    }
    public static void printf(int []sort){
    int p=0;
    for(;;){
    System.out.println(sort[p]+"\\t");
    if(++p>=sort.length)break;
    }
    }

    public static void main(String[] args) {
    int source[] = {1,4,6,9,30,6,7,15,28};
    insertSort(source, 5, source.length);
    }
    }
  • 相关阅读:
    luogu P2639 [USACO09OCT]Bessie的体重问题Bessie's We…
    1001. 害死人不偿命的(3n+1)猜想 (15)
    1003. 我要通过!(20)
    1002. 写出这个数 (20)
    《C语言程序设计(第四版)》阅读心得(一)
    1006. 换个格式输出整数 (15)
    背包问题之多重背包
    背包问题之完全背包
    背包问题之0-1背包
    动态规划例题
  • 原文地址:https://www.cnblogs.com/xinzhuangzi/p/4100592.html
Copyright © 2011-2022 走看看