java写的几个简单排序算法

package sort;

public class Sorts {

	/**
	 * 冒泡排序
	 * @param nums
	 * @return
	 */
	public static int[] bubble(int[] nums) {
		if (nums != null) {
			for (int i = nums.length - 1; i > 0; i--) {
				for (int j = 0; j < i; j++) {
					if (nums[j] > nums[j + 1]) {
						int num = nums[j];
						nums[j] = nums[j + 1];
						nums[j + 1] = num;
					}
				}
			}
		}
		return nums;
	}
	
	/**
	 * 选择排序
	 * @param nums
	 * @return
	 */
	public static int[] selection(int[] nums) {
		if (nums != null) {
			for (int i = nums.length - 1; i > 0; i--) {
				int k = 0;
				for (int j = 1; j <= i; j++) {
					if (nums[k] < nums[j]) {
						k = j;
					}
				}
				if (k != i) {
					int num = nums[k];
					nums[k] = nums[i];
					nums[i] = num;
				}
			}
		}
		return nums;
	}
	
	/**
	 * 插入排序
	 * @param nums
	 * @return
	 */
	public static int[] insertion(int[] nums) {
		if (nums != null) {
			for (int i = 1 ; i < nums.length; i++) {
				int num = nums[i];
				for (int j = i - 1; j >= 0; j--) {
					if (num > nums[j]) {
						nums[j + 1] = num;
						break;
					} else {
						nums[j + 1] = nums[j];
						if (j == 0) {
							nums[0] = num;
						}
					}
				}
			}
		}
		return nums;
	}
	
	/**
	 * 快速排序
	 * @param nums
	 * @param low
	 * @param high
	 * @return
	 */
	public static int[] quick(int[] nums, int low, int high) {
		if (nums != null) {
			if (low >= high) {
				return nums;
			}
			int index = partition(nums, low, high);
			quick(nums, low, index - 1);
			quick(nums, index + 1, high);
		}
		return nums;
	}
	
	/**
	 * 快速排序分区算法
	 * @param nums
	 * @param low
	 * @param high
	 * @return
	 */
	public static int partition(int[] nums, int low, int high) {
		if (nums != null) {
			int key = nums[low];
			while (low < high) {
				while (nums[high] >= key && high > low) {
					high--;
				}
				nums[low] = nums[high];
				while (nums[low] <= key && high > low) {
					low++;
				}
				nums[high] = nums[low];
			}
			nums[high] = key;
		}
		return high;
	}
	
	public static void main(String[] args) {
		int[] nums = {9,8,7,6,5,4,3,1,2,10};
		
		//bubble(nums);
		//selection(nums);
		//insertion(nums);
		quick(nums, 0, nums.length - 1);
		
		for (int num : nums) {
			System.out.print(num + ", ");
		}
		
	}
}

 

你可能感兴趣的:(java,算法)