`
EmmaZhao
  • 浏览: 33437 次
  • 性别: Icon_minigender_2
  • 来自: 北京
最近访客 更多访客>>
社区版块
存档分类
最新评论

排序算法(一)

 
阅读更多
package sort;

public class Sort {
	public static void bubbleSort(int[] numbers){
		for(int i = numbers.length -1 ;i>0;i--){
			for(int j = 0;j<i;j++){
				if(numbers[j] > numbers[j+1]){
					swap(numbers, j, j+1);
				}
			}
		}
		System.out.println("冒泡排序:");
		for (int number : numbers) {
			System.out.print(number + " ");
		}
		System.out.println();
	}
	public static void insertSort(int[] numbers){
		for(int i = 1;i<numbers.length;i++){
			if(numbers[i] < numbers[i-1]){
				int temp = numbers[i];
				int j = i-1;
				for(; (j>=0) &&(temp < numbers[j]);j--){
					numbers[j+1] = numbers[j];
				}
				numbers[j+1] = temp;
			}
		}
		System.out.println("插入排序:");
		for (int number : numbers) {
			System.out.print(number + " ");
		}
		System.out.println();
	}
	public static int[] mergeSort(int[] numbers,int start,int end){
		if(start < end){
			int mid = (start + end)/2;
			
			mergeSort(numbers, start, mid);
			mergeSort(numbers, mid+1, end);
			merge(numbers, start, mid, mid+1, end);
		}
		return numbers;
	}
	public static void selectSort(int[] numbers){
		int min;
		int mink;
		for(int i = 0;i<numbers.length;i++){
			min = numbers[i];
			mink = i;
			for(int j = i;j<numbers.length;j++){
				if(numbers[j] < min){
					min = numbers[j];
					mink = j;
				}
			}
			if(!(min == numbers[i])){
				numbers[mink] = numbers[i];
				numbers[i] = min;
			}
		}
		System.out.println("选择排序:");
		for (int i : numbers) {
			System.out.print(i + " ");
		}
		System.out.println();
	}

	private static void merge(int[] numbers,int start1,int end1,int start2,int end2){
		int i = start1,j = start2;
		int k = 0;
		int temp[] = new int[end2-start1+1];
		while(i <= end1 && j <= end2){
			if(numbers[i] <= numbers[j]){
				temp[k++] = numbers[i++];
			}else{
				temp[k++] = numbers[j++];
			}
		}
		while(i <= end1){
			temp[k++] = numbers[i++];
		}
		while(j <= end2){
			temp[k++] = numbers[j++];
		}
		
		for(int m = 0; m < temp.length;m++){
			numbers[start1 + m] = temp[m];
		}
	}
	private static void swap(int[] numbers,int index1,int index2){
		int temp = numbers[index1];
		numbers[index1] = numbers[index2];
		numbers[index2] = temp;
	}
	public static void main(String[] args) {
		int[] numbers = {456,845,343,421,256,487,487,690,558,455,658,466,677,788,643};
		
		int[] result =mergeSort(numbers, 0, numbers.length-1);
		System.out.println("归并排序:");
		for (int i : result) {
			System.out.print(i + " ");
		}
		System.out.println();
		bubbleSort(numbers);
		selectSort(numbers);
		insertSort(numbers);
	}
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics