Usage of quicksort function in C language (qsort)

  • 2020-05-27 06:40:54
  • OfStack

This article shares the usage of C quicksort function for your reference, the specific content is as follows


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct student
{
  int id;
  char name[12];
  char sex;
};
int compare(const void* a,const void* b)// Basic data type sort 
{
  return *(char*)a-*(char*)b;// Since the childhood 
    // The values // Strong pointer to corresponding type!! 
}
int compare_struct(const void* a,const void* b)
{
  return (*(struct student*)a).id-((struct student*)b)->id;
         // Pay attention to your priorities! // Otherwise error is reported in the unstructured body... 
}
int compare_struct_duoji(const void* a,const void* b)// Multistage sorting 
{
  struct student student_a=*(struct student*)a;
  struct student student_b=*(struct student*)b;

  if(student_a.id==student_b.id)
  {
    return student_a.sex-student_b.sex;
  }
  else
  {
    return student_a.id-student_b.id;
  }
}
void main()
{
//*************char type *************
  char a[5]="hello";
  qsort(a,5,sizeof(a[0]),compare);
      // Number of elements // The element size // A function pointer 
  int i;
  for(i=0;i<5;i++)
      printf("%c ",a[i]);
  printf("\n");

//************struct type ************
  struct student e[4]={{100,"chen",'m'},{100,"li",'f'}, \
             {70,"wang",'f'},{100,"zhang",'m'}};
  qsort(e,4,sizeof(e[1]),compare_struct_duoji);

  for(i=0;i<4;i++)
      printf("%d %s %c\n",e[i].id,e[i].name,e[i].sex);
}

Related articles: