Qsort and sort in a sort

Source: Internet
Author: User

Original: http://www.cnblogs.com/ForeverJoker/archive/2013/05/25/qsort-sort.html

Let's start by explaining Qsort and sort, which can only be sorted on contiguous memory data, such as a list of structures that can't be sorted.

First of all, qsort.

Qsort (a basic fast-sorting method that divides an array into two parts and a dividing value in the middle at a time, and for an array with multiple duplicate values, the basic fast sort is inefficient and unstable). The Qsort function, which is integrated in the C language library function, solves the problem of sorting using the three-way partitioning method. The so-called three-way division, refers to dividing the array into less than the divided value, equal to the dividing value and greater than the divided value of three parts.

Specific Description:-^^

void Qsort (void *base, size_t num, size_t width, int (__cdecl *compare)

int compare (const void *elem1, const void *elem2));

Qsort (ie, quicksort) is mainly based on the comparison criteria you give to a quick sort, mainly through pointer movement to achieve sorting function. The result of sorting is still placed in the original array.

The parameters have the following meanings:

The first parameter base is the name of the target array that needs to be sorted (or it can be understood as an expression that begins sorting, because it can write &s[i])

The second parameter, NUM, is the number of target array elements participating in the sort

The third parameter, width, is the size of a single element (or the length of each element in the target array), and it is recommended to use an expression such as sizeof (S[0])

The fourth parameter compare is a comparison function that makes many people feel very confused.

Let's briefly discuss compare's comparison function (written as compare is my personal preference, you can write anything, like CMP or whatever, and I'll always use CMP to explain it later).

The typical compare definition is the int compare (const void *a,const void *b);

The return value must be int, and the type of the two parameter must be const void *, and that A, B is casually written, personal preference. Assuming that it is an int, if it is ascending, then if a is larger than B, it returns a positive value, a negative value, an equal return of 0, and so on, followed by an example to show how the different types are sorted.

How to use Qsort:

First, sort an array of type int

int num[100];

int cmp (const void *a, const void *b)

{

return * (int *) A-* (int *) b; Sort Ascending

return * (int *) b-* (int *) A; Sort Descending

/* Visible: The parameter list is two null pointers, and now he's going to point to your array elements. So transition to your current type, then take the value.

When sorted in ascending order, if the value of the first parameter pointer is greater than the value that the second parameter pointer points to, returns 0 if the value that the first argument pointer points to is equal to the value that the second parameter pointer points to, or negative if the value of the first argument pointer is less than the value that the second parameter pointer points to.

When sorted in descending order, it is just the opposite.

*/

}

Qsort (S,n,sizeof (s[0]), CMP);

Example full function (already running on VC6.0):

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int s[10000],n,i;
int cmp (const void *a,const void *b)
{
Return (* (int *) b-* (int *) a); The implementation is descending sort
}
int main ()
{

Enter the number of numbers you want to enter
scanf ("%d", &n);
for (i=0;i<n;i++)
scanf ("%d", &s[i]);
Qsort (S,n,sizeof (s[0]), CMP);
for (i=0;i<n;i++)
printf ("%d", s[i]);
return (0);
}

Second, sort the array of char types (same as int type)

Char word[100];

int cmp (const void *a, const void *b)

{

Note that many versions of the Web are "return * (char *) A-* (int *) b; ”

Because the editor's not the heart, blindly copy, baseless assertion, the transmission has been wrong * (int *) b

should be return * (char *) A-* (char *) b;

return * (char *) A-* (char *) b;

}

Qsort (Word,100,sizeof (word[0]), CMP);

Attached, May GetChar (); Will come in handy.

Third, sort the array of double types (especially note)

Double in[100];

int cmp (const void *a, const void *b)

{

return * (double *) a > * (double *) b? 1:-1;

Problem with the return value, it is obvious that CMP is returning an integral type, so avoid a double return decimal and be lost, with a judgment return value.

}

Qsort (In,100,sizeof (in[0]), CMP);

Attached: output of sorted results, generally recommended in "%g" format

/* Here's a word, "%g" format output although the book is that the system will automatically select the "%f" format and "%e" format short-length format, and remove the meaningless 0, but in fact, if the system selected "%e", the system will output more than the "%e" format more than the format output. (This conclusion, the actual operation from VC6.0) */

Iv. sequencing of structural bodies

struct in

{

Double data;

int other;

}S[100]

According to the value of data from small to large structure of the order, about the structure of the key data types can be many, refer to the above example to write

int cmp (const void *a, const void *b)

{

Return (* (in *) a). Data > (* (*) b). Data? 1:-1;

Note that this statement may go wrong in the VC6.0 environment, but it is not the wrong statement, but the first Build or rebuild. In short, the statement is right.

Or you can change the above 1 statements to the following 3 statements

struct in *AA = (in *) A;
struct in *BB = (in *) b;
return aa->data > Bb->data? 1:-1;

}

Qsort (S,100,sizeof (s[0]), CMP);

Five, the structure of the two-level ranking

struct in

{

int x; You can liken it to: the number of failures

int y; You can liken it to: the number of successes

}S[100];

Sort by x from small to large, and when x is equal, sort by y from largest to smallest. You can imagine: failure is the main factor of a problem, the first comparison of fewer failures, the same number of failures to see more success.

int cmp (const void *a, const void *b)

{

struct in *c = (in *) A;

struct in *d = (in *) b;

if (c->x! = d->x) return c->x-d->x;

else return d->y-c->y;

}

Qsort (S,100,sizeof (s[0]), CMP);

Six, sort the string

struct in

{

int data;

Char str[100];

}S[100];

Sort by the dictionary order of the string str in the struct

int cmp (const void *a, const void *b)

{

Return strcmp ((* (in *) a)->str, (* (in *) b)->str);

}

Qsort (S,100,sizeof (s[0]), CMP);

Attention! The CMP in Qsort has to be written by himself.

Say sort (common to C + +)

The sort must be noted: using namespace std; or directly hit Std::sort () plus #include <algorithm> header files

Cases:

#include <iostream>

#include <algorithm>

using namespace Std;

int main ()

{

int a[20];

for (int i=0;i<20;++i)

cin>>a[i];

Sort (a,a+20); Range, it is clear here is a+20 Note that this is necessary if it is a+19

for (i=0;i<20;i++)//Last value a[19] will not participate in sorting.

cout<<a[i]<<endl;

return 0;

}

Std::sort is an improved version of Qsort. The Std::sort function is superior to some features of Qsort: Taking 9 samples for large arrays, a more complete three-way partitioning algorithm, and more meticulous sorting of different array sizes by different methods.

Finally, let's say the difference between sort and qsort:

Sort is an upgrade version of Qsort, if you can use sort as far as possible, use is also relatively simple, not like qsort also have to write the CMP function, as long as the use of the library function can be used, the parameters only two (if the general usage) head pointer and tail pointer;

The default sort is ascending, and if you want to sort it in descending order, you can use your own CMP function

#include <iostream>
#include <algorithm>
using namespace Std;
int cmp (int a,int b)
{
if (a<b)
return 1; In ascending order, if you change to a >b, then descending, note that the return value of CMP () in sort () is only 1 and 0, unlike in Qsort -1!!!!
Else
return 0;
}


int main () {
int i;
int a[20];
for (int i=0;i<5;++i)
cin>>a[i];

Sort (a,a+5,cmp); Range, it's obvious here is a+5 Note that this is necessary if the a+4 last value a[4] will not participate in the sort.
for (i=0;i<5;i++)

cout<<a[i]<<endl;
System ("pause");
return 0;
}

to sort two-dimensional arrays:
#include <iostream>
#include <algorithm>
#include <ctime>
using namespace Std;

BOOL CMP (int *p,int *q)
{
if (P[0]==q[0])
{
if (P[1]==q[1])
{
Return p[2]<q[2];
}
else return p[1]<q[1];
}
else return p[0]<q[0];
}
int main ()
{
Srand (Time (0));
int i;
int **a=new int*[1000];
for (I=0;i<1000;++i)
{
A[i]=new Int[3];
A[i][0]=rand ()%1000;
A[i][1]=rand ()%1000;
A[i][2]=rand ()%1000;
printf ("%d\t%d\t%d\n", a[i][0],a[i][1],a[i][2]);
}
Sort (a,a+1000,cmp);
/*cout<< "after sort" <<endl;
for (I=0;i<1000;++i)
{
printf ("%d\t%d\t%d\n", a[i][0],a[i][1],a[i][2]);
}*/
return 0;
}

Qsort and sort in a sort

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.