选择排序、冒泡排序、插入排序、希尔排序、快速排序

时间:2022-03-07 22:10:55
public class Sort {

	/**
	 * 冒泡排序,对相邻的元素进行两两比较,顺序相反则进行交换,这样,每一趟会将最小或最大的元素“浮”到顶端,最终达到完全有序
	 */
	public static void bubbleSort(int[] a) {
		for (int i = 0; i < a.length; i++) {
			for (int j = 0; j < a.length - 1 - i; j++) {
				if (a[j] > a[j + 1]) {
					int tmp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = tmp;
				}
			}
		}

	}

	/**
	 * 选择排序 ,每一趟从待排序的数据元素中选择最小(或最大)的一个元素作为首元素
	 * 
	 * @param a
	 */
	public static void selectSort(int a[]) {
		for (int i = 0; i < a.length - 1; i++) {
			int min = i;
			for (int j = i + 1; j < a.length; j++) {
				if (a[min] > a[j]) {
					min = j;
				}
			}
			if (min != i) {
				int tmp = a[min];
				a[min] = a[i];
				a[i] = tmp;
			}
		}
	}

	/**
	 * 插入排序,插入排序由N-1趟排序组成,对于p=1到N-1趟,插入排序保证从位置0到位置p上的元素为已排序状态
	 */
	public static void insertionSort(int[] a) {
		int i;
		for (int j = 1; j < a.length; j++) {
			int tmp = a[j];
			for (i = j; i > 0 && a[i - 1] > tmp; i--) {
				a[i] = a[i - 1];
			}
			a[i] = tmp;
		}
	}

	/**
	 * 希尔排序,https://blog.csdn.net/u013967628/article/details/79831518
	 */
	public static void shellSort(int a[]) {
		int i;
		for (int gap = a.length / 2; gap > 0; gap /= 2) {
			for (int j = gap; j < a.length; j++) {
				int tmp = a[j];
				for (i = j; i >= gap && a[i - gap] > tmp; i -= gap) {
					a[i] = a[i - gap];
				}
				a[i] = tmp;
			}
		}
	}

	/**
	 * 快速排序
	 */

	public static void quickSort(int a[], int left, int right) {
		if (left > right) {
			return;
		}
		int temp = a[left];
		int i = left;
		int j = right;
		while (i != j) {
			while (a[j] >= temp && i < j) {
				j--;
			}
			while (a[i] <= temp && i < j) {
				i++;
			}
			if (i < j) {
				int t = a[i];
				a[i] = a[j];
				a[j] = t;
			}
		}
		a[left] = a[i];
		a[i] = temp;
		quickSort(a, left, i - 1);
		quickSort(a, i + 1, right);
	}

	public static void main(String[] args) {
		int a[] = { 34, 8, 64, 51, 32, 21 };
		quickSort(a, 0, a.length - 1);
		for (int i = 0; i < a.length; i++) {
			System.out.print(a[i] + "\t");
		}
	}
}