选择排序(Java实现)--从键盘输入动态数组,并且排序后输出

选择排序

  1. 选择排序思想:

    选择一个最小的,与第一位交换
    除了第一位,选择一个最小的,放在第二位
    除了前两位,选择一个最小的,放在第三位
    以此类推。。。

  2. 代码文件1(Main.java)

package com.dlut.SelectionSort;

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().selectionSort(a);
        new Functions().showAll(a);
    }

}
  1. SelectionSort.java文件
package com.dlut.SelectionSort;

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

public class Functions {
    void selectionSort(ArrayList<Integer> a){
        for(int i=0;i<a.size()-1;i++){
            int index = i;
            for(int j=i+1;j<a.size();j++){
                if(a.get(j)<a.get(index)){
                    index=j;
                }

            }
            if(index!=i){
                int temp=a.get(i);
                a.set(i,a.get(index));
                a.set(index, temp);
            }
            System.out.println("the"+(i)+" th time data");
            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();
    }
}
  1. 运行结果
    这里写图片描述
  2. 其他比较
    这里写图片描述

猜你喜欢

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