数据结构直接插入排序

今天为大家奉上直接插入排序,后续会陆续奉上更多的排序算法,由于本人水平有限,不当之处还请多多指教

import java.util.Scanner;
import org.junit.Test;
public class Main1 {
    /**
     * 直接插入排序
     * @param a 待排序数据
     * @return  排好序的数据(从小到大)
     */
    public static int [] insertSort(int [] a){
        //数据左边界下标
        int left=0;
        //数组右边界下标
        int right=a.length-1;
        /*从后向前搜索
         * (1)如果待排序子数组首元素小于排好序子数组尾元素,将a[i]暂存在temp中
         * (2)temp与a[j](j=i-1,i-2,i-3....0)依次比较,若temp<a[j],则将a[j]后移一个位置
         * (3)当j>=left&&temp<a[j]条件不满足时退出内层循环
         * (4)j+1即为temp要插入的位置
         * */
        for (int i =left+1; i <=right; i++) {
            if(a[i]<a[i-1]){
                int temp=a[i];
                int j=i-1;
                do {
                    a[j+1]=a[j];
                    j--;
                } while (j>=left && temp<a[j]);
                a[j+1]=temp;
            }
        }
        return a;
    }

    @Test
    public void testInsertSort(){
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入数组长度!");
        int n=sc.nextInt();
        int []a=new int[n];

        System.out.println("请输入数组元素");
        for (int i = 0; i < a.length; i++) {
            a[i]=sc.nextInt();
        }

        int [] result=insertSort(a);
        for (int i = 0; i < result.length; i++) {
            System.out.print(result[i]+" ");
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36442947/article/details/80780229