我想让用户输入自己的值,这就是我对这个选择排序代码所拥有的
public class SelectionSort {
public static void main(String args[]){
int[] arr = {5,4,3,2,1}; // This is my array
int min = 0;
for(int i = 0;i<arr.length;i++)
{
//Assume first element is min
min = i;
for(int j = i + 1;j<arr.length;j++)
{
if(arr[j] < arr[min]) { min = j;}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println(arr[i]);//I print the in ascending order
}
}
}
答案 0 :(得分:-1)
在代码中添加以下部分:
Scanner sc = new Scanner(System.in);
System.out.println("No of elements : ");
int noOfElements =sc.nextInt();
int[] arr = new int[noOfElements];
System.out.println("Give elements : ");
for(int i=0;i<noOfElements;i++){
arr[i]= sc.nextInt();
}
您的最终代码如下:
import java.util.Scanner;
public class SelectionSort {
public static void main(String args[]){
// int[] arr = {5,4,3,2,1}; // This is my array
int min = 0;
Scanner sc = new Scanner(System.in);
System.out.println("No of elements : ");
int noOfElements =sc.nextInt();
int[] arr = new int[noOfElements];
System.out.println("Give elements : ");
for(int i=0;i<noOfElements;i++){
arr[i]= sc.nextInt();
}
for(int i = 0;i<arr.length;i++)
{
//Assume first element is min
min = i;
for(int j = i + 1;j<arr.length;j++)
{
if(arr[j] < arr[min]) { min = j;}
}
int temp = arr[i];
arr[i] = arr[min];
arr[min] = temp;
System.out.println("Sorted Elemenst : "+arr[i]);//I print the in ascending order
}
}
}