冒泡排序我们再熟悉不过了,简单方便易实现。只是实现的效率肯定是很低的,时间复杂度为O(n²)。
下面是我简单写的排序:
public class BubbleSort {
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static void sort(int [] a){
int len=a.length;
for(int i=0;i<len-1;i++){
for(int j=i;j<len-1;j++){
if(a[i]>a[j]){
swap(a,i,j);
}
}
}
}
public static void main(String[] args){
int a[] = { 1, 4, 7, 2, 8, 0, 3, 6, 5, 9 };
for (int s : a) {
System.out.print(s + " ");
}
System.out.println();
sort(a);
for (int s : a) {
System.out.print(s + " ");
}
}
}