冒泡排序

来源:互联网 发布:互联网金融 加班 知乎 编辑:程序博客网 时间:2024/05/22 05:28

普通冒泡排序:

/** * 对无序数组进行排列,两两比较,使得大数在后。 */public class BubbleSortTest {public static void bubbleSort(int[] array) {//比较趟数,共比较(array.length-1)趟for (int i = 1; i < array.length; i++) {//每趟两两比较次数,每趟比较(array.length-i)次for (int j = 0; j < array.length - i; j++) {//前面的数大于后面的数,则交换位置if (array[j] > array[j + 1]) {int temp = array[j];array[j] = array[j + 1];array[j + 1] = temp;}}}System.out.println("排序后的结果为:");for (int i = 0; i < array.length; i++) {System.out.print(array[i] + " ");}}public static void main(String[] args) {int[] array = {2, 5, 1, 6, 8, 7, 4, 6, 9, 3};bubbleSort(array);}}


改进后的冒泡排序(改进后的冒泡排序内层循环判断出有序后,便不再进行循环,在一定程度提高了效率):

/** * 改进后的冒泡排序算法的实现: */public class ImprovedBubbleSort {public static void improvedBubbleSort(int[] list) {boolean needNextPass = true;for (int k = 1; k < list.length && needNextPass; k++) {needNextPass = false;for (int i = 0; i < list.length - k; i++) {if (list[i] > list[i + 1]) {int temp = list[i];list[i] = list[i + 1];list[i + 1] = temp;needNextPass = true;}}}}//测试public static void main(String[] args) {int[] array = new int[10];for (int k = 0; k < array.length; k++) {array[k] = (int) (Math.random() * 100);}System.out.println("Before Sorting:");for (int k = 0; k < array.length; k++) {System.out.print(array[k] + "  ");}System.out.println("\n\nAfter Sorting:");improvedBubbleSort(array);for (int k = 0; k < array.length; k++) {System.out.print(array[k] + "  ");}}}


0 0
原创粉丝点击