import java.util.Scanner;
public class Test3 {
public static void home(int[] arr) {
System.out.println("-----------原数据-----------");
output(arr);
Scanner sc = new Scanner(System.in);
int number;
while (true) {
System.out.println("----1 升序 2 降序 3 退出----");
number = sc.nextInt();
switch (number) {
case 1:
insert_sort(arr);
output(arr);
break;
case 2:
select_resort(arr);
output(arr);
break;
case 3:
System.out.println("程序退出");
System.exit(0);
default:
System.out.println("您的选择有误");
}
}
}
public static void output(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
if (i != arr.length - 1) {
System.out.print(",");
}
}
System.out.println();
}
public static int[] insert_sort(int[] arr) {
System.out.println("------------升序-------------");
int i, j, k, temp;
for (i = 1; i < arr.length; i++) {
for (j = i - 1; j >= 0; j--) {
if (arr[j] < arr[i]) {
break;
}
}
if (j != i - 1) {
temp = arr[i];
for (k =i-1; k >j; k--) {
arr[k+1]=arr[k];
}
arr[k+1] =temp;
}
}
return arr;
}
public static int[] select_resort(int[] arr) {
System.out.println("------------降序-------------");
int temp;
for (int i = 0; i < arr.length-1; i++) {
int index=i;
for (int j=i+1;j<arr.length;j++) {
if(arr[j]>arr[index]) {
index=j;
}
}
temp=arr[index];
arr[index]=arr[i];
arr[i]=temp;
}
return arr;
}
public static void main(String[] args) {
int[] arr = { 87, 68, 94, 85, 59, 33, 83, 75, 82, 52 };
home(arr);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/30f5f82e5a6bab60477c964dfc678b60.png)