基础冒泡排序

import java.util.Arrays;

/**
 * This program demonstrates bubble sort. 冒泡排序的实现方式及优化,个人练习,如有错误请大侠指出
 */

public class BubbleSortImpro {

	public static void main(String[] args) {
		int[] a = { 3, 5, 10, 4, 1 };
		bubbleSort1(a);
		System.out.println("The 1 result: " + Arrays.toString(a));

		int[] b = { 3, 5, 10, 4, 1 };
		bubbleSort2(b);
		System.out.println("The 2 result: " + Arrays.toString(b));

		int[] c = { 3, 5, 10, 4, 1 };
		bubbleSort3(c);
		System.out.println("The 3 result: " + Arrays.toString(c));
	}

	// 第一种实现:(前两种实现都是稳定排序)
	private static void bubbleSort1(int[] arr) {
		for (int i = 0; i < arr.length - 1; i++)
			for (int j = 0; j < arr.length - 1 - i; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = 0;
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
	}

	// 第二种实现:
	private static void bubbleSort2(int[] arr) {
		for (int i = arr.length - 1; i > 0; --i)
			for (int j = 0; j < i; ++j) {
				if (arr[j] > arr[j + 1]) {
					int temp = 0;
					temp = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = temp;
				}
			}
	}

	// 第三种实现;省略了中间的多次交换,这种实现使冒泡排序变成了不稳定排序(参考来的....)
	private static void bubbleSort3(int[] arr) {
		for (int i = arr.length - 1, max = 0; i > 0; max = 0, --i) {
			for (int j = 1; j < i; ++j) {
				if (arr[j] > arr[max])
					max = j;
			}
			if (arr[max] > arr[i]) {
				int temp = 0;
				temp = arr[max];
				arr[max] = arr[i];
				arr[i] = temp;
			}
		}
	}
}

Java初学者



posted @ 2014-02-21 17:20  _better  阅读(191)  评论(0编辑  收藏  举报