Summary of several sorts (middle)--quick sort

Source: Internet
Author: User
Quick Sort Key Features

1) Normal fast sort worst time complexity O (n^2)

2) Expected time complexity of O (NLGN)

3) Small constants contained in O (NLGN)

4) in-place sorting, no auxiliary array space required
Main Operation 1. Array partitioning

In the fast sorting algorithm, the key is to select a base value, the array is divided into larger than the base value and a small base value of two parts, and return the basis value so in the position of the benefit for recursive division.

The following first describes the Lomuto partitioning method.

Array A, set the need to divide a section of a[p]~a[r], we expect the result is to get a Q, wherein P<=q<=r, makes A[p]~a[q-1]<=a[q]<=a[q+1]~a[r], At this point the original array was divided into three parts.

First, set the base value to the last element of the array a[r], and we hope that the result is a[r] now the corresponding value in the end of the algorithm can be ranked in the middle of the two parts than his and small love.

then make i=p-1; J=p, when A[j]>x is found, J moves on and does not need any movement. When A[j]<=x is found, we need to put this element on one side less than the base value, so I add 1, and exchange the element at this time a[i], with A[j], and then J self-add 1. This time I points to the last element of the data that is smaller than the base value, and J points to the first remaining element that has not been judged.

The above step loops continuously until J points to R, at which time only R is not determined with the base value, whereas A[r] is originally the base value, and except for A[r], A[p]~a[i] is the part of the base value, A[i+1]~a[r-1] is greater than the basic value of the part, so at this time just exchange a[i+1] and a[ R].

This part of the algorithmic complexity is O (n) because the results are obtained from the first scan of the array A.
2. Recursive ordering

After dividing the entire array first, we divide the array into two parts, some smaller than the base value, some larger than the base value, and we know where the base value is located, set to Q, so we simply recursively sort the divided two parts.

In the worst case, a portion of the size of each partition is 0, part of the n-1, in which case the recursive division is N Times, the time complexity is O (n^2)

In a slightly better case, a partial size of one-tenth and a portion size of nine-tenths are given each time, in which case there is a recursive formula:

T (n) ≤t (9N/10) + T (N/10) + (n) = O (n lg N)
In the average case, when the best and worst cases occur in turn, the worst-case scenario has little effect on the progressive time, so the time complexity is O (NLGN)
3. randomization

Randomized processing randomly selects one of the areas that need to be partitioned as a baseline, which allows for better averaging performance.
Other Discussions
1.hoare Division

The main principle of this division and the above division principle is similar, the difference is that the division will be the base element is also divided into a group, the resulting is two groups. Specific as follows:

For array A, the interval is p~r, the first element of the region is set as the X=a[p],i,j initial point to the two ends of the region, I and J are close to each other, when encountering a[j]<x,a[i]>x, two elements are exchanged, I point to the last element is smaller than the baseline, J points to elements that are larger than the base. The loop continues until the end of the I==j cycle, at which point the array is divided into two parts by the I or J demarcation.

This algorithm is also scanned once the array can be completed, so the time complexity of O (n)
2.stooge Sorting

The principle of stooge sorting is to divide the array into three parts, first sorting the first 2/3 of the group, then sorting the last 2/3 of the group, and then sorting the first 2/3 of the group. The recursive formula is T (N) =3t (2N/3) +o (1), according to the main theorem, the time complexity is O (N^log (3/2,3)) ~=o (n^2.7)

See http://ufownl.blog.163.com/blog/static/1250122200861072445895/
3. Eliminate the tail recursion

Because the quicksort second recursive call is not necessary, so you can use the loop instead of the tail recursion, the implementation is shown in the following code QUICKSORT2
4. Three number of

In order to better get the datum elements, you can use random selection of three elements, and then take the way to optimize the method, the implementation of the following code three_randomized_partition
5. Interval Fuzzy sorting

The n intervals [Ai,bi] are sorted so that a CI belongs to [Ai,bi], satisfies the C1<=C2<=......<=CN, and uses a quick sort to transform the implementation.

Reference: http://cnicwsh.iteye.com/blog/504394, implementation code see final.

Problem Description:

Consider a sort of problem in which you cannot accurately know exactly how many numbers are to be sorted. For each of these numbers, we only know that it falls within a certain interval on the real axis. That is, given is a closed interval of n shape such as [A (i), B (i)] (here, the role of subscript, after the same), where a (i) <= B (i). The object of the algorithm is to sort these intervals in fuzzy order (Fuzzy-sort), that is, to produce a permutation of each interval <i (1), I (2), ..., I (n), so that there is a C (j) belonging to

interval [A (I (j)), B (i (j))], meet C (1) <= C (2) <= C (3) <= ... <= c (n).

A) design an algorithm for the fuzzy ordering of n intervals. Your algorithm should have the general structure of the algorithm, it can quickly sort the left end (ie, each a (i)), but also to make full use of overlapping intervals to improve the running time. (as each interval overlaps more and more, the problem of fuzzy sorting of each interval becomes more and more easy.) Your algorithm should be able to take full advantage of this overlap. )

b) prove that: In general, your algorithm expects to run at θ (NLGN), but when all the intervals overlap, the desired run time is θ (n) (i.e., when there is a value of x, so that all I, there is x∈[a (i), B (i)]). Your algorithm should not examine this situation explicitly, but should improve performance naturally as the amount of overlap increases.

Algorithm idea:

By using the idea of fast sorting algorithm, the interval sequence is divided. But at this point the main element interval element is the common interval (intersection) of all the interval elements in a set of interval elements.

That is, all the interval elements in the set are "equal" or "arbitrary order is ordered". Initially, the algorithm optionally takes an interval element as the main element (same as fast sort).

When the algorithm runs, if an interval element is strictly smaller than the main element, it is placed to the left of the sequence, and if it is strictly greater than the main element, it is placed to the right of the sequence, otherwise, the interval element intersects with the main element, the update of the main element interval is the interval portion of the intersection, and the interval element is added In the set of interval elements. After the current sequence is processed, the left and right sub-sequences are recursively processed (divide-and-conquer ideas, with quick sorting).

In the course of the procedure, the overlapping parts will be eliminated continuously, if all the parts overlap, it is completed at the first partition, when the time is O (n)


The normal quick sort code is as follows:

#include <stdio.h> #include <algorithm> #include <stdlib.h> #include <time.h> using namespace
Std
int a[100];
int b[100];

int c[100];
	void Stooge_sort (int *a,int I,int j) {if (A[i]>a[j]) swap (a[i],a[j]);
	if ((i+1) >=j) return;
	int k= (J-I+1)/3;
	Stooge_sort (A,I,J-K);
	Stooge_sort (A,I+K,J);
Stooge_sort (A,I,J-K);
	} int partion (int *a, int p, int r) {int x=a[r];
	int i=p-1;
			for (int j=p; j<r; J + +) {if (a[j]<=x) {i++;
		Swap (a[i],a[j]);
	}} swap (A[i+1],a[r]);
return i+1;
		} void quicksort (int *a, int p, int r) {if (p<r) {int q=partion (A,P,R);
		Quicksort (a,p,q-1);
	Quicksort (A,Q+1,R);
		}} void Quicksort2 (int *a, int p, int r) {while (p<r) {int q=partion (A,P,R);
			if (q-p<r-q) {quicksort2 (a,p,q-1);
		p=q+1;
			} else{Quicksort2 (a,q+1,r);
		R=q-1;
	}}} int moare_partion (int *a,int p,int r) {int x=a[p];
	int i=p-1;
	int j=r+1;
		while (1) {do{j--;
		}while (A[J]&LT;X);
		do{i++;
		}while (A[I]&GT;X); If(i<j) Swap (a[i],a[j]);
	else return J;
		}} void Moare_quicksort (int *a, int p, int r) {if (p<r) {int q=moare_partion (A,P,R);
		Moare_quicksort (A,P,Q);
	Moare_quicksort (A,Q+1,R);
	}} int randomized_partition (int *a, int p, int r) {Srand (Time (NULL));
	I~[P,R] int I=p+rand ()% (r-p+1);
	Swap (a[i],a[r]);
Return partion (A,P,R);
		} void Randomized_quicksort (int*a, int p, int r) {if (p<r) {int q=randomized_partition (A,P,R);
		Randomized_quicksort (a,p,q-1);
	Randomized_quicksort (A,Q+1,R);
	}} int three_randomized_partition (int *a, int p, int r) {Srand (Time (NULL));
    I~[P,R] int I=p+rand ()% (r-p+1);
    int J=p+rand ()% (r-p+1);
	int K=p+rand ()% (r-p+1); if (j<=k&&k<=i| |
	I&LT;=K&AMP;&AMP;K&LT;=J) i=k; if (k<=j&&j<=i| |
	I&LT;=J&AMP;&AMP;J&LT;=K) I=j;
	Swap (a[i],a[r]);
Return partion (A,P,R);
		} void Three_randomized_quicksort (int *a, int p, int r) {if (p<r) {int q=three_randomized_partition (A,P,R); Three_randomized_quiCksort (a,p,q-1);
	Three_randomized_quicksort (A,Q+1,R);
	}} int main () {int len;
	scanf ("%d", &len);
	for (int i=1; i<=len; i++) {scanf ("%d", &a[i]);
}//Quicksort2 (A,1,len);
Moare_quicksort (A,1,len);
Stooge_sort (A,1,len);
	Three_randomized_quicksort (A,1,len);
	Randomized_quicksort (A,1,len);
		for (int j=1; j<=len; J + +) {if (J!=len) printf ("%d", a[j]);
	else printf ("%d\n", A[j]);
} return 0;
 }


Interval Fuzzy Quick Sort code:

#include <stdio.h> using namespace std;
	Class array{Public:int begin;
	int end;
			Array () {} array (int a, int b) {if (a<=b) {this->begin=a;
		this->end=b;
			} else{this->begin=0;
		this->end=0;

}
	}
};
	Array swap (array*a, int x, int y) {array tmp;
	TMP=A[X];
	A[x]=a[y];
a[y]=tmp; }//Divide the array into three segments//a section is less than the datum main element section, this part of the array subscript from P~I-1//Two segment is the part that overlaps with the datum principal, this part of the array subscript is from I~J//three segment is greater than the datum of the part, this part of the array subscript from J+1~R// Use k in the process to indicate the next array element to be judged//recursion will return two integers i,j, used to mark the next recursion to start the place//use the array type as the return only to store i,j, the flag and datum overlap part, does not represent a segment array
	Partition (array *a, int p, int r) {array x=a[p];
	int i=p;
	int k=p+1;
	int j=r;
			while (K&LT;=J) {//The current region is less than the base main element region if (A[k].end<x.begin) {swap (a,i,k);
			i++;
		k++;
			}//The current region is greater than the base main element region else if (a[k].begin>x.end) {swap (a,j,k);
		j--;
			}//The current region has overlapping else{in the Datum master area x.begin=a[k].begin>x.begin?a[k].begin:x.begin;
			x.end=a[k].end<x.end?a[k].end:x.end;
		k++;
}} return Array (i-1,j+1); } void Quicksort (Array *a, int p, int r) {if (p< r) {Array q=partition (a,p,r);
		Quicksort (A,p,q.begin);
	Quicksort (A,Q.END,R);
	}} int main () {array A[6]={array (2,4), array (0,1), array (5,6), Array (3,3), array (1,5), Array (8,9)};
	Quicksort (a,0,5);
	for (int i=0; i<6; i++) {printf ("[%d,%d]", a[i].begin,a[i].end);
} printf ("\ n");
 }


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.