Summary of how to use sort () and qsort () in C + +

Source: Internet
Author: User
Tags strcmp

When and algorithm specific explanation please see dot me

Think of themselves every day sort of sort, bubbling ah, binary search Ah, the results in the STL with the sorting function Sort,qsort, finally freed himself ~
So I summed up a bit, first look at the sort function in the following table:

Description of functions of function names
Sort sorts all elements of a given interval
Stable_sort stable ordering of all elements in a given interval
Partial_sort ordering of all elements in a given interval
Partial_sort_copy copying and sorting for a given interval
Nth_element find the corresponding element in a given interval
Is_sorted Infer If an interval has been sequenced.
Partition to put elements that meet a certain condition in front
Stable_partition is relatively stable so that elements that meet a certain condition are placed in front

To use this function it is only possible to use # include <algorithm> sort, which is described in the syntax description:
Sort (begin,end), which represents a range, such as:
int _tmain (int argc, _tchar* argv[])
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for (i=0;i<20;i++)
cout<<a[i]<<endl;
Sort (a,a+20);
for (i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
The output would be to sort the array a in ascending order, and perhaps someone would ask how to use it in descending order? This is what the next discussion is about.
One is to write a comparison function to implement, and then call the three-parameter Sort:sort (begin,end,compare). For the list container, this method is also applicable, the compare as a sort of the parameter can be, namely: sort (Compare).

1) Write your own compare function:
BOOL Compare (int a,int b)
{
Return a<b; In ascending order, if you change to return a>b, then descending
}
int _tmain (int argc, _tchar* argv[])
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for (i=0;i<20;i++)
cout<<a[i]<<endl;
Sort (a,a+20,compare);
for (i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}

2) Further, make this operation more adaptable to change. That is, the function can be given a reference to indicate whether it is sorted in ascending or descending order, which turns to the function object's appearance.
To describe convenience, I first define an enumeration type, Enumcomp, to represent ascending and descending. Very easy:
Enum ENUMCOMP{ASC,DESC};
It then starts with a class describing the function object. It determines whether to use "<" or ">" depending on its number of references.

Class Compare
{
Private
Enumcomp comp;
Public
Compare (Enumcomp C): Comp (c) {};
BOOL operator () (int num1,int num2)
{
Switch (COMP)
{
Case ASC:
Return num1<num2;
Case DESC:
Return num1>num2;
}
}
};

Next use Sort (Begin,end,compare (ASC) to implement ascending, sort (Begin,end,compare (DESC) implementation in descending order.
The main functions are:
int main ()
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for (i=0;i<20;i++)
cout<<a[i]<<endl;
Sort (A,a+20,compare (DESC));
for (i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
3) In fact for such a simple task (type support for "<", ">" and other comparison operators), it is not necessary to write a class themselves. The standard library already has a ready-made, in the functional, include comes in. Functional provides a stack of template-based comparative function objects. They are (see name to know meaning):equal_to<type>, not_equal_to<type>, greater<type>, greater_equal<type>, Less<type>, less_equal<type>. For this problem, greater and less are enough to come straight to use:

Ascending: Sort (begin,end,less<data-type> ());
Descending: Sort (begin,end,greater<data-type> ()).
int _tmain (int argc, _tchar* argv[])
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for (i=0;i<20;i++)
cout<<a[i]<<endl;
Sort (a,a+20,greater<int> ());
for (i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
4) Since there is an iterator, it is assumed that a string is able to use a reverse iterator to complete reverse order, such as the following:
int main ()
{
String str ("cvicses");
String s (Str.rbegin (), Str.rend ());
cout << S <<endl;
return 0;
}
Qsort ():
Prototype:
_crtimp void __cdecl qsort (void*, size_t, Size_t,int (*) (const void*, const void*));
Explanation: Qsort (array name, number of elements, space occupied by elements (sizeof), comparative function)
The comparison function is a self-written function that follows the format of the int COM (const void *a,const void *b).
When a-B relationship is > < =, a positive negative value of 0 (or vice versa) is returned respectively.
When you use a B to cast the type, the operation is performed after the type of the response is converted from void *.
Array subscript starts from zero, the number is N, subscript 0-(n-1).
Instance:
int compare (const void *a,const void *b)
{
return * (int*) b-* (int*) A;
}
int main ()
{
int a[20]={2,4,1,23,5,76,0,43,24,65},i;
for (i=0;i<20;i++)
cout<<a[i]<<endl;
Qsort (void *) a,20,sizeof (int), compare);
for (i=0;i<20;i++)
cout<<a[i]<<endl;
return 0;
}
Related:
1) Why do you have to give the number of elements?
Because the array does not know how many elements it has
2) Why do you have to give size?
Because Qsort does not know the units it wants to sort.
3) Why do you have to write the ugly function that is used to compare two values?
Since qsort requires an indicator to point to a function, it does not know the type of element it is ordering.
4) Why Qsort accepts a const void* argument instead of a char* argument for a comparison function used by?
Because qsort can sort the values of non-strings.
Of course there are other ways to use sorting functions, just say this today, I am also learning, the above is just a little bit of their own humble opinion, the final statement of appeal is based on vc++2008.

Two-dimensional character array sorting

#include <iostream> #include <cstring> #include <algorithm>using namespace std;struct Data{char data[ 100];} Str[100];bool CMP (const data &ELEM1, const data &elem2) {if (strcmp (Elem1.data, Elem2.data) < 0) return True;ret Urn false;} int main () {int n, i;while (cin>>n) {for (i=0; i<n; ++i) {cin>>str[i].data;} Sort (str, str+n, CMP); for (i=0; i<n; ++i) Cout<<str[i].data<<endl;} return 0;}


Code two:

BOOL CMP (const char *ELEM1, const char *elem2) {if (strcmp (elem1, ELEM2) < 0)  return true; return false;} int main () {char str[100][100]; char *pstr[100] = {NULL}; int n, I; while (cin>>n) {for  (i=0; i<n; ++i)  {   cin>>str[i];    Pstr[i] = Str[i];   }  Sort (pStr, pstr+n, CMP);  for (i=0; i<n; ++i)   cout<<pstr[i]<<endl;} return 0;}



Qsort ()

#include <iostream> #include <algorithm>using namespace Std;int cmp (const void *a,const void *b) {  return strcmp ((char*) A, (char *) b);} struct Tel{char phone[10];} Tel[10];int Main () {   int cases;   int i;   cin >> cases;   Char tel[20][10];   for (i = 0; i < cases; ++i)   cin >> Tel[i];   Qsort (tel,cases,sizeof (char) *10,cmp);   for (int j = 0; J < i; ++j)   cout << tel[j] << Endl;}



Summary of how to use sort () and qsort () in C + +

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.