常用java排序

import java.util.Random;

/**
 * @author alaahong
 * 
 */
public class JavaSort {

	private static void swap(int[] array, int i, int j) {
		int temp = array[i];
		array[i] = array[j];
		array[j] = temp;
	}

	private static void printData(int[] data) {
		for (int i : data) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	public static int[] createArray(int n) {
		Random random = new Random();
		int[] array = new int[n];
		for (int i = 0; i < n; i++) {
			array[i] = random.nextInt(100);
		}
		printData(array);
		return array;
	}

	/**
	 * 冒泡排序
	 * 
	 * @author alaahong
	 * @param data
	 */
	public void bubbleSort(int[] data) {
		for (int i = 0; i < data.length; i++) {
			for (int j = i; j < data.length - 1; j++) {
				if (data[j] > data[j + 1])
					swap(data, j, j + 1);
			}
		}
		printData(data);
	}

	/**
	 * 选择排序
	 * 
	 * @author alaahong
	 * 
	 */
	public void selectSort(int[] data) {
		int index = 0;
		for (int i = 0; i < data.length; i++) {
			index = i;
			for (int j = i; j < data.length; j++) {
				if (data[index] > data[j])
					index = j;
			}
			if (index != i)
				swap(data, i, index);
		}
		printData(data);
	}

	/**
	 * 插入排序
	 * 
	 * @author alaahong
	 */
	public void insertSort(int[] data) {
		int temp = 0;
		for (int i = 1; i < data.length; i++) {
			int j = i - 1;
			temp = data[i];
			for (; j >= 0 && temp < data[j]; j--) {
				data[j + 1] = data[j];
			}
			data[j + 1] = temp;
		}
		printData(data);
	}

	/**
	 * 希尔排序
	 * 
	 * @author alaahong
	 */
	public void shellSort(int[] data) {
		int ss = data.length >> 1;
		int temp = 0;
		while (ss >= 1) {
			for (int i = ss; i < data.length; i++) {
				int j = i - ss;
				temp = data[i];
				while (j >= 0 && data[j] > temp) {
					data[j + ss] = data[j];
					j = j - ss;
				}
				data[j + ss] = temp;
			}
			ss >>= 1;
		}
		printData(data);
	}

	/**
	 * 快速排序
	 * 
	 * @author alaahong
	 */
	public void quickSort(int[] data) {
		quick(data, 0, data.length - 1);
		printData(data);
	}

	public void quick(int[] data, int low, int high) {
		int i, j, x;
		if (low < high) {
			i = low;
			j = high;
			x = data[i];
			while (i < j) {
				while ((data[j] >= x) && (i < j)) {
					j--;
				}
				if (i < j) {
					data[i] = data[j];
					i++;
				}
				while ((data[i] <= x) && (i < j)) {
					i++;
				}
				if (i < j) {
					data[j] = data[i];
					j--;
				}
				data[i] = x;
				quick(data, low, j - 1);
				quick(data, j + 1, high);
			}
		}
	}

	/**
	 * 反转数组
	 * 
	 * @author alaahong
	 * 
	 */
	public void reverse(int[] data) {

		for (int i = 0; i < (data.length >> 1); i++) {
			swap(data, i, data.length - 1 - i);
		}
		printData(data);
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		JavaSort js = new JavaSort();
		js.quickSort(createArray(10));
	}

}


你可能感兴趣的:(常用java排序)