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

我会带着你远行 2022-05-28 03:07 279阅读 0赞

插入排序

排序思想:

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

    相关代码实现

  • 第一个JAVA文件(Main.java)

    package com.dlut.insertSort;

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

    public class Main {

    1. public static void main(String[] args) {
    2. Scanner sc = new Scanner(System.in);
    3. System.out.println("please input the data,press \"CTRL+Z\" to end input");
    4. ArrayList<Integer> a = new ArrayList<Integer>();
    5. while(sc.hasNext()){
    6. int temp;
    7. temp= sc.nextInt();
    8. a.add(temp);
    9. }
    10. new Functions().showAll(a);
    11. new Functions().insertSort(a);
    12. new Functions().showAll(a);
    13. }

    }

  • 第二个Java文件

    package com.dlut.insertSort;

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

    public class Functions {

    1. void insertSort(ArrayList<Integer> a){
    2. for(int i=1;i<a.size();i++){
    3. int j=i-1;
    4. int temp=a.get(i);
    5. while(j>=0&&a.get(j)>a.get(i)){ //这里要巧用while循环
    6. a.set(j+1, a.get(j));
    7. j--;
    8. }
    9. a.set(j+1, temp);
    10. showAll(a);
    11. }
    12. }
    13. void showAll(ArrayList<Integer> a){
    14. System.out.println("please show the data");
    15. Iterator<Integer> it = a.iterator();
    16. while(it.hasNext()){
    17. System.out.print(it.next()+"\t");
    18. }
    19. System.out.println();
    20. }

    }

执行结果

这里写图片描述

其他比较

这里写图片描述

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读