(数据结构与算法分析 八)------插入排序,希尔排序,归并排序的实现( Java语言描述)

首先是插入排序,原理没什么好说的

package com.bird.seven;
/**
 * 插入排序的实现
 * @author Bird
 *
 */
public class InsertSort {
	
	public static void insertSort(int[] a){
		int j;
		for(int i = 1; i < a.length; i++){
			int temp = a[i];
			
			for(j = i; j > 0 && temp < a[j-1]; j--)
				a[j] = a[j-1];
			a[j] = temp;
		}
	}
	
	public static void main(String[] args){
		int[] a = {34,8,64,51,32,21};
		insertSort(a);
		for(int t : a)
			System.out.print(t+" ");
	}
}

运行结果为

8 21 32 34 51 64 

然后是希尔排序

package com.bird.seven;
/**
 * 希尔排序的实现
 * @author Bird
 *
 */
public class ShellSort {
	
	public static void shellSort(int [] a){
		for(int gap = a.length/2; gap > 0; gap /= 2){
			for(int i = gap; i < a.length; i++){
				int temp = a[i];
				int j = i;
				
				for(; j >= gap&&temp < a[j-gap]; j -= gap)
					a[j] = a[j-gap];
				a[j] = temp;
			}
		}
	}
	
	
	public static void main(String [] args){
		int [] a = {81,94,11,96,12,35,178,95,28,58,41,75,15};
		shellSort(a);
		for(int t : a)
			System.out.print(t + " ");
	}
}

运行结果为

11 12 15 28 35 41 58 75 81 94 95 96 178 

归并排序为

package com.bird.seven;
/**
 * 归并排序的实现
 * @author Bird
 *
 */
public class MergeSort {
	
	public static void mergeSort(int[] a, int[] temp, int left, int right){
		if(left < right){
			int center = (left + right)/2;
			mergeSort(a,temp,left,center);
			mergeSort(a,temp,center+1,right);
			merge(a,temp,left,center+1,right);
		}
	}
	
	public  static void mergeSort(int [] a){
		int [] temp = new int [a.length];
		mergeSort(a,temp,0,a.length-1);
	}

	private static void merge(int[] a, int[] temp, int leftPos, int rightPos, int rightEnd) {
		int leftEnd = rightPos -1;
		int tmpPos = leftPos;
		int numElements = rightEnd - leftPos + 1;
		
		while(leftPos <= leftEnd && rightPos <= rightEnd){
			if(a[leftPos] <= a[rightPos])
				temp[tmpPos++] = a[leftPos++];
			else
				temp[tmpPos++] = a[rightPos++];
			
			while(leftPos <= leftEnd)
				temp[tmpPos++] = a[leftPos++];
			
			while(rightPos <= rightEnd)
				temp[tmpPos++] = a[rightPos++];
			
			for(int i = 0 ; i < numElements; i++, rightEnd--){
				a[rightEnd] = temp[rightEnd];
			}
		}
	}
	
	
	public static void main(String [] args){
		int [] a = {81,94,11,96,12,35,178,95,28,58,41,75,15};
		mergeSort(a);
		for(int t : a)
			System.out.print(t + " ");
	}
}

运行结果为

11 12 15 28 35 41 58 75 81 94 95 96 178 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值