冒泡排序
package test;
class Main {
public static void main(String[] args) {
int a[] = { 2, 4, 6, 12, 1, 7 };
sort(a);
show(a);
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
public static void sort(int[] a) {
for (int i = 1; i < a.length; i++) {
boolean f = false;
for (int j = 0; j < a.length - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
f = true;
}
}
if (!f)
break;
}
}
}
选择排序
package test;
class Main {
public static void main(String[] args) {
int a[] = { 2, 4, 6, 12, 1, 7 };
sort(a);
show(a);
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
}
public static void sort(int[] a) {
int min;
for (int i = 0; i < a.length; i++) {
min = i;
for (int j = i + 1; j < a.length; j++) {
if (a[j] < a[min]) {
min = j;
}
}
if (min != i) {
int temp;
temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}
}
}