这三种排序的时间复杂度都是指数级的,所以在实际项目中并不推荐。
/**
* Created by Administrator on 2018-02-17.
*/
public class Sort {
static final int SIZE = 10;
public static void BubbleSort(int[] a) {
int temp;
if(a.length > 1) {
for (int i = 1; i < a.length; i++) {
for (int j = 0;j < a.length - i;j++) {
if(a[j] > a[j+1]) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
System.out.print("第" + i +"步排序结果:");
for (int k = 0;k < a.length;k++) {
System.out.print(" " + a[k]);
}
System.out.print("\n");
}
}
}
public static void selectSort(int[] a) {
int index;
int temp;
for (int i = 0;i < a.length - 1;i++) {
index = i;
for (int j = i + 1;j < a.length;j++) {
if(a[j] < a[index]) {
index = j;
}
}
if(index != i) {
temp = a[i];
a[i] = a[index];
a[index] = temp;
}
System.out.print("第" + i + "步排序结果:");
for (int h = 0;h < a.length;h++) {
System.out.print(" " + a[h]);
}
System.out.print("\n");
}
}
public static void insertionSort(int[] a) {
int i,j,t,h;
for (i = 1;i < a.length;i++) {
t = a[i];
j = i - 1;
while (j >= 0 && t < a[j]) {
a[j+1] = a[j];
j--;
}
a[j+1] = t;
System.out.print("第" + i + "步排序结果:");
for (h = 0;h < a.length;h++) {
System.out.print(" " + a[h]);
}
System.out.print("\n");
}
}
public static void main(String[] args) {
int[] shuzu = new int[SIZE];
int i;
for (i = 0;i < SIZE;i++) {
shuzu[i] = (int)(100 + Math.random() * (100 + 1));
}
System.out.print("排序前的数组为:\n");
for (i = 0;i <SIZE;i++) {
System.out.print(shuzu[i] + " ");
}
System.out.print("\n");
BubbleSort(shuzu); //selectSort或者insertionSort
System.out.print("排序后的数组为:\n");
for (i = 0;i < SIZE;i++) {
System.out.print(shuzu[i] + " ");
}
System.out.print("\n");
}
}