java算法:冒泡排序
java算法:冒泡排序
冒泡排序:不断遍历文件,交换倒序的相邻元素,直到文件排好顺序。冒泡排序的主要优点是容易实现,冒泡排序通常会比选择排序、插入排序慢。
如,对EXAMPLE 字母进行排序:
E X A M P L E .开始
[A] E X [E] M P L .E移到了A之后,A移到了最前面
A E [E] X L M P .L移到了E之后,E移到了X前面
A E E [L] X M P .L移到了X前面
A E E L [M] X P ...
A E E L M [P] X
A E E L M P [X]
- public class Bubble {
- public static void main(String[] args) {
- int n = 20;
- MyItem [] a = new MyItem[n];
- for (int i = 0; i < n; i++) {
- a[i] = new MyItem();
- a[i].rand();
- }
- for (int i = 0; i < n; i++) {
- System.out.print(a[i] + " ");
- }
- bubble(a, 0, n);
- System.out.println("");
- print(a, n);
- }
- private static void print(MyItem a [], int n){
- for (int i = 0; i < n; i++) {
- System.out.print(a[i] + " ");
- }
- }
- public static void bubble(MyItem [] a, int l, int r){
- for (int i = l; i < r; i++) {
- for (int j = r - 1; j > i; j--) {
- compExch(a, j - 1, j);
- }
- }
- }
- public static boolean less(Item v, Item w){
- return v.less(w);
- }
- public static void exch(Item [] a, int i, int j){
- Item t = a[i];
- a[i] = a[j];
- a[j] = t;
- }
- public static void compExch(Item [] a, int i, int j){
- if(less(a[j],a[i])){
- exch(a, i, j);
- }
- }
- }