排序算法分为九种,分别为:冒泡排序(bubble)、
一、冒泡排序 bubble
冒泡排序 是不断的走访要排序的数列,每次比较两个数,如果位置错误,就交换过来,直到没有在需要交换的数为止。
动态示意图参考:
http://visualgo.net/sorting
java 代码实现如下:
package com.sort;
public class BubbleSortTest {
public static void main(String[] args) {
int[] intArray = new int[]{3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48};
bubbleSort(intArray);
System.out.print("" + "{ ");
for (int i = 0; i < intArray.length; i++) {
System.out.print(intArray[i]);
//控制格式化输出,最后一个输不需要“,”
if (i == intArray.length - 1) {
System.out.print(" ");
} else {
System.out.print(", ");
}
}
System.out.println("" + " }");
}
//冒泡排序 使用两层for循环
public static void bubbleSort(int[] array){
int temp;
//第一层for循环控制 找到一个最大数
for (int j = 0; j < array.length -1; j++) {
//第二层for循环 控制找到一个最大数,需要两个数比较多少次
for (int i = 0; i < array.length - 1 - j; i++) {
if (array[i] > array[i + 1]) {
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}
}
冒泡排序结果如下:
{ 2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50 }