1. 基础版
每次从剩余待排元素中找到最小值放到待排元素最前面,共n-1轮
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[i]) {
int t = a[i];
a[i] = a[j];
a[j] = t;
}
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
2. 基础优化版
不是在选数过程中进行交换,而是找到最小元素后再交换
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
for (int i = 0; i < n; i++)
a[i] = sc.nextInt();
for (int i = 0; i < a.length - 1; i++) {
int mIdx = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[mIdx])
mIdx = j;
}
if (mIdx != i) {
int t = a[i];
a[i] = a[mIdx];
a[mIdx] = t;
}
}
for (int i = 0; i < n; i++) {
System.out.print(a[i] + " ");
}
}
}
复杂度
时间复杂度:严格O(n)
空间复杂度:O(1)