A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 小懒猫 中级黑马   /  2017-10-23 21:02  /  692 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

[Java] 纯文本查看 复制代码
import java.util.Arrays;

public class SortTest {

	public static void main(String[] args){
		
		int[] a = {2,4,3,7,5,8,1,6};
		
		System.out.println("使用插入排序:"+ Arrays.toString(insertSort(a)));
		System.out.println("使用二分插入排序:"+ Arrays.toString(binaryInsertSort(a)));
		System.out.println("使用冒泡排序:"+ Arrays.toString(bubble(a)));
		System.out.println("使用快速排序:" + Arrays.toString(quickSort(a, 0, a.length-1)));
		
	}
	

	/**
	 * 插入排序
	 * 步骤:将无序数列中的数与有序数列依次比较,插入合适的位置,直至整个数列有序
	 * @param numbers
	 * @return
	 */
	public static int[] insertSort(int[] numbers){
		
		for (int i = 0; i < numbers.length; i++){
			for (int j = i; j > 0; j--){
				if (numbers[j] < numbers[j-1]){
					int temp = numbers[j];
					numbers[j] = numbers[j-1];
					numbers[j-1] = temp;
				}				
			}
		}
		
		return numbers;
	}
	
	
	/**
	 * 二分插入排序
	 * @param numbers
	 * @return
	 */
	public static int[] binaryInsertSort(int[] numbers){
		
		for (int i = 1; i < numbers.length; i++){
			if (numbers[i] < numbers[i-1]){
				int temp = numbers[i];
				int left = 0;
				int right = numbers.length - 1;
				while (left <= right){
					int mid = (left + right) / 2;
					if (numbers[mid] < temp){
						left += 1;
					} else {
						right -= 1;
					}
				}
				for (int j = i; j > left; j--){
					numbers[j] = numbers[j-1];
				}
				numbers[left] = temp;
			}   
		}
		
		return numbers;
	}
	
	/**
	 * 冒泡排序
	 * 步骤:1.依次比较相邻两个数的大小,将大数放在小数后面
	 * 		2.重复步骤1至排序结束
	 * @param numbers
	 */
	public static int[] bubble(int[] numbers){
		int temp = 0;
		int len = numbers.length - 1;
		
		for (int i = 0; i < len; i++){
			for (int j = 0; j < len - i; j++){
				if (numbers[j] > numbers[j+1]){
					temp = numbers[j];
					numbers[j] = numbers[j+1];
					numbers[j+1] = temp;
				}
			}
		}
		return numbers;
	}
	
	/**
	 * 快速排序
	 * @param numbers
	 * @param low
	 * @param high
	 * @return
	 */
	public static int[] quickSort(int[] numbers, int low, int high){
		
		if (low < high){
			int mid = getMid(numbers, low, high);
			quickSort(numbers, low, mid - 1);
			quickSort(numbers, mid + 1, high);
		}
		
		return numbers;
	}
	public static int getMid(int[] numbers, int low, int high){
		
		int temp = numbers[low];
		while (low < high){
			 while (numbers[high] > temp){
				 high--;
			 }
			 numbers[low] = numbers[high];
			 while (numbers[low] < temp){
				 low++;
			 }
			 numbers[high] = numbers[low];
		}
		numbers[low] = temp;
		
		return low;
	}
	
}

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马