试题 基础练习 数列排序
资源限制
时间限制:1.0s 内存限制:512.0MB
问题描述
给定一个长度为n的数列,将这个数列按从小到大的顺序排列。1<=n<=200
输入格式
第一行为一个整数n。
第二行包含n个整数,为待排序的数,每个整数的绝对值小于10000。
输出格式
输出一行,按从小到大的顺序输出排序后的数列。
样例输入
5
8 3 6 4 9
样例输出
3 4 6 8 9
冒泡排序
import java.io.BufferedInputStream;
import java.util.Scanner;
/**
* @author huxuyang
* @create 2021-12-07 10:07
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < n; i++) {
for (int j = 1; j < n; j++) {
if (arr[j]<arr[j-1]){
int temp = arr[j];
arr[j] = arr[j-1];
arr[j-1] = temp;
}
}
}
System.out.print(arr[0]);
for (int i = 1; i < n; i++) {
System.out.print(" " + arr[i]);
}
}
}
使用Arrays.sort()排序
package lanqiao;
import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;
/**
* @author huxuyang
* @create 2021-12-07 10:07
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(new BufferedInputStream(System.in));
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
Arrays.sort(arr);
System.out.print(arr[0]);
for (int i = 1; i < n; i++) {
System.out.print(" " + arr[i]);
}
}
}
单层for循环排序
import java.util.Scanner;
/**
* @author huxuyang
* @create 2021-12-07 10:07
*/
public class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = scan.nextInt();
}
for (int i = 0; i < n-1; i++) {
int temp = arr[i];
if (arr[i+1]<arr[i]){
arr[i] = arr[i+1];
arr[i+1] = temp;
i = -1;
}
}
System.out.print(arr[0]);
for (int i = 1; i < n; i++) {
System.out.print(" " + arr[i]);
}
}
}