JAVA排序算法实现代码-冒泡(Bubble Sort)排序
-
-
-
-
-
-
- public class Test {
- public static void main(String[] args) {
- int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 };
-
- System.out.print("排序前: ");
-
- for (int i = 0; i < a.length; i++)
- System.out.printf("%3s", a[i]);
-
- System.out.println();
-
- Test test = new Test();
- test.bubbleSort(a);
-
- System.out.print("排序后: ");
-
- for (int i = 0; i < a.length; i++)
- System.out.printf("%3s", a[i]);
-
- System.out.println();
- }
-
- public void bubbleSort(int[] a) {
- int len = a.length;
-
- System.out.println("数组大小是:" + len);
-
- boolean change = false;
- int temp;
- int count = 0;
-
- for (int i = len; i > 1; i--) {
- for (int j = 0; j < i - 1; j++) {
- if (a[j + 1] < a[j]) {
- temp = a[j + 1];
- a[j + 1] = a[j];
- a[j] = temp;
- change = true;
- count++;
- }
-
- }
- if (change) {
- System.out.print("第" + count + "趟交换: ");
- for (int k = 0; k < len; k++)
- System.out.print(a[k] + " ");
-
- System.out.println();
- }
- }
- }
- }
/**
* JAVA排序算法实现代码-冒泡(Bubble Sort)排序。
*
* @author 老紫竹 JAVA世纪网(java2000.net)
*
*/
public class Test {
public static void main(String[] args) {
int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 };
System.out.print("排序前: ");
for (int i = 0; i < a.length; i++)
System.out.printf("%3s", a[i]);
System.out.println();
Test test = new Test();
test.bubbleSort(a);
System.out.print("排序后: ");
for (int i = 0; i < a.length; i++)
System.out.printf("%3s", a[i]);
System.out.println();
}
public void bubbleSort(int[] a) {
int len = a.length;
System.out.println("数组大小是:" + len);
boolean change = false;
int temp;
int count = 0;
for (int i = len; i > 1; i--) {
for (int j = 0; j < i - 1; j++) {
if (a[j + 1] < a[j]) {
temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
change = true;
count++;
}
}
if (change) {
System.out.print("第" + count + "趟交换: ");
for (int k = 0; k < len; k++)
System.out.print(a[k] + " ");
System.out.println();
}
}
}
}
运行结果
排序前: 10 32 1 9 5 7 12 0 4 3
数组大小是:10
第8趟交换: 10 1 9 5 7 12 0 4 3 32
第15趟交换: 1 9 5 7 10 0 4 3 12 32
第20趟交换: 1 5 7 9 0 4 3 10 12 32
第23趟交换: 1 5 7 0 4 3 9 10 12 32
第26趟交换: 1 5 0 4 3 7 9 10 12 32
第29趟交换: 1 0 4 3 5 7 9 10 12 32
第31趟交换: 0 1 3 4 5 7 9 10 12 32
第31趟交换: 0 1 3 4 5 7 9 10 12 32
第31趟交换: 0 1 3 4 5 7 9 10 12 32
排序后: 0 1 3 4 5 7 9 10 12 32