Review how to implement the bubble sorting...
package com.pc.tmp;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class TryBubbleSort {
/**
* @param args
*/
public static void main(String[] args) {
// 1. Gen the int array randomly
int len = 10;
int[] arr = new int[len];
int cnt = 0;
Random random = new Random();
System.out.print("int array randomly generated: ");
for (int i = 0; i < len; i++) {
arr[i] = (int) (Math.random() * 100);
System.out.print(arr[i] + ", ");
}
System.out.println();
// 2. start to do bubble sorting
System.out.println("start bubble sorting on it.. ");
for (int i = 0; i < len - 1; i++) {
for (int j = 0; j < len - i - 1; j++) {
if (arr[j] < arr[j + 1]) {
int tmp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = tmp;
System.out.print("sorting: ");
printArr(arr);
}
cnt++;
}
}
System.out.println("total loop times: " + cnt);
System.out.print("after sorted: ");
printArr(arr);
// 两两相比:将最小的升到最后面去。这样最后面的数就无须再次参与比较了!
}
private static void printArr(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + ", ");
}
System.out.println();
}
}
int array randomly generated: 93, 42, 49, 30, 60, 35, 52, 25, 46, 18,
start bubble sorting on it..
sorting: 93, 49, 42, 30, 60, 35, 52, 25, 46, 18,
sorting: 93, 49, 42, 60, 30, 35, 52, 25, 46, 18,
sorting: 93, 49, 42, 60, 35, 30, 52, 25, 46, 18,
sorting: 93, 49, 42, 60, 35, 52, 30, 25, 46, 18,
sorting: 93, 49, 42, 60, 35, 52, 30, 46, 25, 18,
sorting: 93, 49, 60, 42, 35, 52, 30, 46, 25, 18,
sorting: 93, 49, 60, 42, 52, 35, 30, 46, 25, 18,
sorting: 93, 49, 60, 42, 52, 35, 46, 30, 25, 18,
sorting: 93, 60, 49, 42, 52, 35, 46, 30, 25, 18,
sorting: 93, 60, 49, 52, 42, 35, 46, 30, 25, 18,
sorting: 93, 60, 49, 52, 42, 46, 35, 30, 25, 18,
sorting: 93, 60, 52, 49, 42, 46, 35, 30, 25, 18,
sorting: 93, 60, 52, 49, 46, 42, 35, 30, 25, 18,
total loop times: 45
after sorted: 93, 60, 52, 49, 46, 42, 35, 30, 25, 18,