JAVA经典算法50题(12)
时间:2026-01-19
时间:2026-01-19
)
import java.util.Arrays;
public class Demo34 {
public static void main(String[] args) {
int[] arrays = { 800, 56, 500 };
Arrays.sort(arrays);
for (int n = 0; n < arrays.length; n++)
System.out.println(arrays[n]);
}
}
或
if(x > y) { int t = x; x = y; y = t; } if(x > z) { int t = x; x = z; z = t; } if(y > z) { int t = y; y = z; z = t; }
【程序35】 题目:输入数组,最大的与第一个元素交换,最小的与最后一个元素交换,输出数组。
import java.util.*;
public class Demo35 {
public static void main(String[] args) {
int i, min=0, max=0, n, temp1, temp2;
int a[];
System.out.println("定义数组的长度:");
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new int[n];
for (i = 0; i < n; i++) {
System.out.print("输入第" + (i + 1) + "个数据:");
a[i] = in.nextInt();
}
for (i = 1; i < n; i++) {
if (a[i] > a[max])
max = i;
if (a[i] < a[min])
min = i;
}
temp1 = a[0];
a[0] = a[max];
a[max] = temp1;
temp2 = a[min];
if (min != 0) { // 如果最小值不是a[0],执行下面
a[min] = a[n - 1];
a[n - 1] = temp2;
} else { //如果最小值是a[0],执行下面
a[max] = a[n - 1];
a[n - 1] = temp1;
}
for (i = 0; i < n; i++) {
System.out.print(a[i] + " " );
}
}
}
【程序36】 题目:有n个整数,使其前面各数顺序向后移m个位置,最后m个数变成最前面的m个数
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class Demo36 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("输入数字个数n:");
int n = in.nextInt();
System.out.println("输入后移位数m:");
int m = in.nextInt();
LinkedList<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < n; i++) {
System.out.println("请输入第"+(i+1)+"个数:");
list.add(in.nextInt());
}
System.out.println("原数据排序为:");
for (int t : list) {
System.out.print(t + " " );
}
System.out.println();
List<Integer> temp1 = list.subList(list.size() - m, list.size());
List<Integer> temp2 = list.subList(0, list.size() - m);
temp2.addAll(0, temp1);
System.out.println("移动后排序为:");
for (int t : temp2) {
System.out.print(t + " " );
}
}
}
或
import java.util.*;
public class Demo36{
public static void main(String[] args){
Scanner in=new Scanner(System.in);
System.out.println("请定义数组的长度:");
int n=in.nextInt();
System.out.println("请输入移动的位数:");
int m=in.nextInt();
int [] arr=new int [n];
int [] brr=new int [n];
for(int i=0;i<n;i++){
System.out.println("请输入第"+(i+1)+"个数:");
arr[i]
=in.nextInt();
}
System.out.println("排序前:");
for(int i=0;i<n;i++){
System.out.print(arr[i]+" ");
}
System.out.pri