选择排序

  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. 其他比较
    这里写图片描述
Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐