經典的氣泡排序法 JAVA實現
阿新 • • 發佈:2019-02-12
public
class BubbleSort { /** *@paramargs *@authorwu,yaowen*@paramargs */ //initialize the array by Math.random() publicint[] initArray(int arrLen){ int len = arrLen; int a[] = newint[len]; for(int i=0; i<len; i++){a[i] = (
int)(Math.random()*100);}
return a;}
// End of initArray() //print the array publicSystem.
out.print(a[i] + " ");}
}
// End of printArray //taxis the array publicvoid bubbleSort(int arr[]) { for (int i = 0; i < arr.length; i++) { // for 1round j, chose the biggest number; for (int j = 0; j < arr.length - i - 1; j++) {arr[j + 1] = arr[j];
arr[j] = t;
}
}
// End of 2nd For}
}
// End of bubbleSort() publicstaticvoid main(String[] args) { // TODO Auto-generated method stub finalint ARRAY_SIZE = 10; int a[] = newint[ARRAY_SIZE];BubbleSort b =
new BubbleSort();a = b.initArray(ARRAY_SIZE);
/**
for(inti=0;i<ARRAY_SIZE; i++){ a[i]=(int)(Math.random()*100); }*/
//print the original arraySystem.
out.println("The original order of the array is: ");b.printArray(a);
/**
for(inti=0;i< a.length; i++) { System.out.print(a[i]+""); }*/
b.bubbleSort(a);
System.
out.println("/n/nAfter sorted, the order of the array is: ");b.printArray(a);
/**
for(inti=0;i< a.length; i++) { System.out.print(a[i]+""); }*/
} // End of main()}
out put(by random):
The original order of the array is:
65 92 21 15 33 98 64 9 20 50
After sorted, the order of the array is:
9 15 20 21 33 50 64 65 92 98