冒泡排序是java基础学习的基本功,综合性相对较强,也很锻炼逻辑能力,综合了数组、for循环以及基本的排序思想。
public class MAOPAO {
public static void main(String[] args) {
int[] a = { 2, 5, 8, 20, 0, 1, 4, 3, 10, 13 };
int t = 0;
for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
t = a[j];
a[j] = a[j + 1];
a[j + 1] = t;
}
}
}
for (int j = 0; j < a.length; j++) {
System.out.println(a[j]);
}
}
}
基本的冒泡会了,升降序稍微想一下还是很容易实现的:
冒泡与升降序:
public static void main(String[] args) {
int[] arr = new int[5];
Scanner scan = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
System.out.println("请输入第" + (i + 1) + "个元素的值:");
arr[i] = scan.nextInt();
}
// BubbleSort
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
int temp = 0;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
System.out.println("升序后的结果为:");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
// SelectionSort
for (int i = 0; i < arr.length - 1; i++) {
for (int j = i + 1; j < arr.length; j++) {
if (arr[i] < arr[j]) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println("降序后的结果为:");
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
System.out.println("最大值是:" + arr[0] + ",最小值是:" + arr[arr.length - 1]);
}
}