A brief discussion on the fast ordering of different types of data by Qsort function

Source: Internet
Author: User
Tags strcmp

First, sort an array of type int

int num[100];

int cmp (const void *a, const void *b)
{
return * (int *) A-* (int *) b;
}

Qsort (Num,100,sizeof (num[0]), CMP);

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

Char word[100];

int cmp (const void *a, const void *b)
{
return * (char *) A-* (int *) b;
}

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

Third, sort the array of double type

Double in[100];

int cmp (const void *a, const void *b)
{
return * (double *) a > * (double *) b? 1:-1;
}

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

Iv. sequencing of structural bodies

struct Sample
{
Double data;
int other;
}S[100]

Sort by data value from small to general structure

int cmp (const void *a, const void *b)
{
Return (* (sample *) a). Data > (* (sample *) b). Data? 1:-1;
}

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

Five, the structure of the two-level ranking

struct Sample
{
int x;
int y;
}S[100];

Sort by x from small to large, when x is equal by y from largest to smallest

int cmp (const void *a, const void *b)
{
struct Sample *c = (sample *) A;
struct Sample *d = (sample *) 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 Sample
{
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 ((* (sample *) a). STR, (* (sample *) b). str);
}

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

Append a full point code, sort the two-dimensional array of strings:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

Char s[2001][1001];

int cmp (const void *a, const void *b) {
Return strcmp ((char *) A, (char *) b);
}

int main () {
int i,n;
scanf ("%d", &n);
GetChar ();
for (i=0;i<n;i++) gets (S[i]);
Qsort (S,n,1001*sizeof (char), CMP);
For (i=0;i<n;i++) puts (s[i]);
return 0;
}

A brief discussion on the fast ordering of different types of data by Qsort function

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.