左神-初级-二讲-快排(标准+改进版)

标准版,每次确定一个元素位置


public class leet832__1 {
	    public static void main(String[] args) {
	    	int[] a= {2,1,33,5,43,222,3,12};
	    	quickSort(a,0,a.length-1);
	    	for(int i:a) {
	    		System.out.println(i);
	    	}
	    }
		public static void quickSort(int[] a,int low,int high) {
			if(low<high) {//这个条件千万不要忘,我总是忘
				int temp=position(a,low,high);
				quickSort(a,low,temp-1);
				quickSort(a,temp+1,high);
			}
		}
		public static int position(int[] a,int low,int high) {
			int jizhun=a[low];
			while(low<high) {
				while(low<high&&a[high]>jizhun) {
					high--;
				}
				swap(a,low,high);
				while(low<high&&a[low]<=jizhun) {
					low++;
				}
				swap(a,low,high);
			}
			a[low]=jizhun;
			return low;
		}
		public static void swap(int[] a,int low,int high) {
			int temp=a[low];
			a[low]=a[high];
			a[high]=temp;
		}
}

改进版,每次确定一些相等的元素位置

public class Leetcode160 {
	public static void main(String[] args) {
		int[] a= {2,1,33,5,43,222,3,12};
    	quickSort(a,0,a.length-1);
    	for(int i:a) {
    		System.out.println(i);
    	}
	}
	public static void quickSort(int[] arr, int l, int r) {
		if (l < r) {
			int[] p = partition(arr, l, r);
			quickSort(arr, l, p[0] - 1);
			quickSort(arr, p[1] + 1, r);
		}
	}
	public static int[] partition(int[] arr,int l,int r) {
		int low=l-1;
		int cur=l;
		while(cur<=r) {//和左神不一样,我这个必须有等号,因为最后一个元素可能没放对。
			if(arr[cur]<arr[l]) {
				swap(arr,++low,cur++);
			}else if(arr[cur]>arr[l]) {
				swap(arr,cur,l);
			}else {
				cur++;
			}
		}
		return new int[] {low+1,l};
	}
	public static void swap(int[] arr, int i, int j) {
		int tmp = arr[i];
		arr[i] = arr[j];
		arr[j] = tmp;
	}

}

如果再改进,就是随机快排,就一句花,生成一个随机位置于第一项换

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值