Analysis of ranking function qsort () function

I.
Usage: * qsort is included in < cstdlib > header file

• The functions are sorted quickly according to the given comparison conditions, and the sorted results are still in the original array.
• Using the qsort() function, you have to write a comparison function by yourself
qsort() function format: qsort (array name, number of array elements, number of bytes per element, comparison function)
II:
(1) Sorting integer arrays in ascending order
#include <iostream>
#include <cstdlib>
using namespace std;
int cmp ( const void *a , const void *b )
{int *c=(int *)a;        //(int*) is mandatory type conversion
int *d=(int *)b;
return *c-*d;          //Equivalent to = return *(int *)b- *(int *)a; in descending order, return * D - * c;
}
int main()
{
int a={4,2,7,3,6,1,5};
int i,n=7;
qsort(a, n,sizeof(a),cmp);      //sizeof() is a monocular operator with no header file
for(i=0;i<n;i++)
cout<<a[i]<<",";
}

(2) Sorting char-type arrays in ascending order

#include <iostream>
#include <cstdlib>
#include <cstring>
using namespace std;
int cmp ( const void *a , const void *b )
{
char *c=(char *)a;       //(char*) is mandatory type conversion
char *d=(char *)b;
return *c-*d;
}
int main()
{
char str="gjlfjsder";
int i,n;
n=strlen(str);
qsort(str, n,sizeof(str),cmp);
puts(str);
}

(3) Ascending Sort of Arrays of double Type

#include <iostream>
#include <cstdlib>
using namespace std;
int cmp ( const void *a , const void *b )
{
double *c,*d;
c=(double *)a;
d=(double *)b;
return *c>*d ? 1 : -1;
}
int main()
{
double a= {5, 2.5, 1.3, 3.2};
int i,n=4;
qsort(a, n,sizeof(a),cmp);
for(i=0; i<n; i++)
cout<<a[i]<<",";
cout<<endl;
}

(4) Primary sorting of structured arrays (from large to small according to the value of the results)

int cmp( const void *a ,const void *b)
{
struct student *c, *d;
c=(struct student *)a;
d=(struct student *)b;
return  d->score – c->score;   //Descending order
}

struct student
{
char name;
int score;
} stu;

Call: qsort(stu,100,sizeof(stu),cmp)
(5) Secondary ranking of structured arrays (ranking from large to small according to the value of the results, and ascending according to the names of those with the same results)

int cmp( const void *a ,const void *b)
{
struct student *c, *d;
c=(struct student *)a;
d=(struct student *)b;
if(d->score!=c->score)
return  d->score – c->score;   //Descending order
else  //Achievements are the same, in ascending order by name
return strcmp(c->name, d->name);
}
struct student
{
char name;
int score;
} stu;

Call: qsort(stu,100,sizeof(stu),cmp)
2: sort and qsort
There is not much difference in essence. Sort is from small to large by default. In short, sort can be used with sort.
Note that the header file of sort is # include < algorithm >

Posted by map200uk on Wed, 09 Oct 2019 23:36:17 -0700