Quick-Arrange two ways

Source: Internet
Author: User
Method One: First from right to left than base small number, and then from left to right to find than base of the number, and finally is smaller than the base of the number on the left, than the base size of the number on the right.
void qsort (int *a, int l, int r) {
	if (l<r) {
		int i=l;
		int j=r;
		int base=a[l];
		int tmp;
		while (I<J) {while
			(I<j&&base<=a[j]) {
				j--;
			}
			while (I<j&&base>=a[i]) {
				i++
			}
			if (i<j) {
				tmp=a[j];
				A[j]=a[i];
				A[i]=tmp
		   }
		}
		A[l]=a[i];
		A[i]=base;
		Qsort (a,l,i-1);
		Qsort (a,i+1,r);
	}






Method Two: From left to right to traverse, divided into less than region-equal region-greater than the region, and then recursively less than the region and greater than the region
void swap (int arr[],int i, int j) {
	int tmp = arr[i];
	Arr[i] = arr[j];
	ARR[J] = tmp;
}
void partition (int a[],int l, int r,int *lef,int *rgt) {
	int less=l-1;
	int more=r;
	while (L<more) {
		if (A[l]<a[r]) {
			swap (a,++less,l++);
		} else if (A[l]>a[r]) {
			swap (a,--more,l);
		else{
			l++
		}
	}
	Swap (a,more,r);
	*lef=less+1;
	*rgt=more;
}


void quicksort (int a[],int l,int r) {
	if (l<r) {
		int lef,rgt;
		Partition (A,L,R,&LEF,&RGT);
		Quicksort (a,l,lef-1);
		Quicksort (a,rgt+1,r);
	}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.