插入排序(Java实现)---从控制台输入不定长数组,并输出排序结果

插入排序

排序思想:

  • 对前两个数据进行排序,较大的放后面
  • 将第三个数据插入到前两个数据中,放在合适的位置
  • 相应数据后移

    相关代码实现

  • 第一个JAVA文件(Main.java)
package com.dlut.insertSort;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("please input the data,press \"CTRL+Z\" to end input");
        ArrayList<Integer> a = new ArrayList<Integer>();
        while(sc.hasNext()){
                int temp; 
                temp= sc.nextInt();
                a.add(temp);
            }
        new Functions().showAll(a);
        new Functions().insertSort(a);
        new Functions().showAll(a);
    }

}
  • 第二个Java文件
package com.dlut.insertSort;

import java.util.ArrayList;
import java.util.Iterator;

public class Functions {
    void insertSort(ArrayList<Integer> a){
        for(int i=1;i<a.size();i++){
            int j=i-1;
            int temp=a.get(i);
            while(j>=0&&a.get(j)>a.get(i)){ //这里要巧用while循环
                a.set(j+1, a.get(j));
                j--;
            }
            a.set(j+1, temp);
            showAll(a);

        }
    }

    void showAll(ArrayList<Integer> a){
        System.out.println("please show the data");
        Iterator<Integer> it = a.iterator();
        while(it.hasNext()){
            System.out.print(it.next()+"\t");
        }
        System.out.println();
    }
}

执行结果

这里写图片描述

其他比较

这里写图片描述

猜你喜欢

转载自blog.csdn.net/siying8419/article/details/79728345