笔记--JAVA实现排序

插入排序

对于给定的一组记录,初始时假定第一个记录自成一个有序的序列,其余的记录为无序序列;接着从第二个记录开始,按照记录的大小依次将当前处理的记录插入到其之前的有序序列中,直至最后一个记录插入到有序序列为止。时间复杂度为O(n^2),空间复杂度O(1);稳定排序。

	//插入排序
	public static int[] insertSort(int[] i){
		int tmp = 0;
		for (int j = 0;j<i.length;j++){
			for(int count = j;count > 0;count--){
				if(i[count]<i[count-1]){
					tmp = i[count];
					i[count] = i[count-1];
					i[count-1]=tmp;
				}else{
					break;
				}
			}
		}
		return i;
	}

冒泡排序

对于给定的n个记录,从第一个记录开始依次对相邻的两个记录进行比较,当前面的记录大于后面的记录时,交换其位置,进行一轮比较和交换位置后,n个记录中的最大记录将位于第n位;然后对前(n- 1)个记录进行第二轮比较;重复该过程直到进行比较的记录只剩下一个为止。时间复杂度为O(n^2),空间复杂度O(1);稳定排序。

	//冒泡排序
	public static int[] maopao(int[] i){
		int tmp = 0;
		for(int j = 0; j < i.length-1; j++){
			for(int k = 0 ; k<i.length-1-j ; k++){
				if(i[k+1]<i[k]){
					tmp = i[k+1];
					i[k+1] = i[k];
					i[k]=tmp;
				}
			}
		}
		return i;
	}

快速排序

对于一组给定的记录,通过一趟排序后,将原序列分为两部分,其中前部分的所有记录均比后部分的所有记录小,然后再依次对前后两部分的记录进行快速排序,递归该过程,直到序列中的所有记录均为有序为止。时间复杂度为O(nlogn),空间复杂度O(nlogn);不稳定排序。

	//快速排序
	public static int[] sort(int[] a,int start,int end){
		if(start<end){
			int center=kuai(a, start, end);
			sort(a, center+1, end);
			sort(a,start,center-1);
		}
		return a;
	}
	public static int kuai(int[] a,int start,int end){
		int center =a [start];
		while(start < end){
			while(start<end&&center<=a[end])
				end--;
			a[start]=a[end];
			while(start<end&&center>=a[start])
				start++;
			a[end]=a[start];
		}
		a[end]=center;
		return end;
	}

选择排序

对于给定的一组记录,经过第一轮比较后得到最小的记录,然后将记录与第一个记录的位置进行交换;接着对不包括第一个记录以外的其他记录进行第二轮排序,得到最小的记录并与第二个记录进行位置交换;重负该过程,直到进行比较的记录只有一个为止。时间复杂度为O(n^2),空间复杂度O(1);不稳定排序。

	//选择排序
	public static int[] select(int[] a){
		int index = 0;
		int tmp = 0;
		for(int i = 0;i<a.length-1;i++){
			for(int j = i;j<a.length;j++){
				if(a[j]<a[index]){
					index=j;
				}
			}
			tmp = a[i];
			a[i]=a[index];
			a[index]=tmp;
		}
		return a;
	}

堆排序

时间复杂度为O(nlogn),空间复杂度O(1);不稳定排序。

	//堆排序
	public static void firstSort(int[] array){
		//大根堆
		for(int start = (array.length-1)/2;start>=0;start--){
			adjust(array, start,array.length);
		}
	}
	//调整树结构从start节点
	public static void adjust(int[] array, int start,int length){
		int tmp = 0;
		int rem = array[start];
		while(start*2+1<length){
			tmp = 2*start+1;
			//找出左右子树中值更大的一方
			//可能出现数组越界的问题(不存在右子树)
			if(start*2+2<length){
				if(array[2*start+1] < array[start*2+2]){
					tmp = start*2+2;
				}
			}
			if(array[start] < array[tmp]){
				array[start]=array[tmp];
			}else{
				break;
			}
			start=tmp;
		}
		array[start]= rem ;
	}
	
	public static int[] dui(int[] array){
		firstSort(array);
		for(int i = array.length-1; i>0;i--){
			int tmp = array[i];
			array[i] = array[0];
			array[0] = tmp;
			adjust(array, 0, i);
		}
		return array;
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值