经典的冒泡排序法 JAVA实现

 

public

class BubbleSort { /** * @param args * @author wu, yaowen * @param args */ //initialize the array by Math.random() public int[] initArray(int arrLen){ int len = arrLen; int a[] = new int[len]; for(int i=0; i<len; i++){

a[i] = (

int)(Math.random()*100);

}

return a;

}

// End of initArray() //print the array public void printArray(int a[]){ for (int i = 0; i < a.length; i++) {

System.

out.print(a[i] + " ");

}

}

// End of printArray //taxis the array public void 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++) { if (arr[j + 1] < arr[j]) { int t = arr[j + 1];

arr[j + 1] = arr[j];

arr[j] = t;

}

}

// End of 2nd For

}

}

// End of bubbleSort() public static void main(String[] args) { // TODO Auto-generated method stub final int ARRAY_SIZE = 10; int a[] = new int[ARRAY_SIZE];

BubbleSort b =

new BubbleSort();

a = b.initArray(ARRAY_SIZE);

/**

for(int i =0; i<ARRAY_SIZE; i++){ a[i]=(int)(Math.random()*100); }

*/

//print the original array

System.

out.println("The original order of the array is: ");

b.printArray(a);

/**

for (int i = 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 (int i = 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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值