package com.zwj;
import java.util.Scanner;
public class SelsetArrayTest {
/**
* 主函数
*/
public static void main(String[] args){
int arr[] = new int[5];
userInput(arr);
selectSort(arr);
printArray(arr);
}
/**
* 核心方法,选择排序
*/
public static void selectSort(int arr[]){ //这里注意该方法必须是static才可以被main函数直接调用
for(int x=0; x<arr.length-1; x++){ //注意这里要退一位,最后一位数没必要自己和自己比
for(int y=x+1; y<arr.length; y++){
if(arr[x] > arr[y]){ //较大的数和较小的数左右互调位置,然后继续和下一个角标的数比较,根据大小
int temp = arr[x]; //继续互换位置
arr[x] = arr[y];
arr[y] = temp;
}
System.out.println(" ");
}
}
}
/**
* 打印
*/
public static void printArray(int arr[]){ //多余功能,添加括号
System.out.print("[");
for(int i=0; i<arr.length; i++){
if(i!= arr.length-1){
System.out.print(arr[i] + ",");
}else{
System.out.print(arr[i] + "]");
}
}
}
/**
* 用户输入
*/
public static void userInput(int[] arr){
Scanner input = new Scanner(System.in);
System.out.println("请输入5个需要比较的数字:");
for(int i=0; i<arr.length; i++){
arr[i] = input.nextInt();
}
}
}
选择排序
最新推荐文章于 2024-10-05 15:09:26 发布