C语言:qsort排序的实现

/* qsort example */
#include <stdio.h>      /* printf */
#include <stdlib.h>     /* qsort */
#include<string.h>

 struct S
{
 char name[20];
 int age;
};
 /*int compare(const void*x, const void *y)
 {
  int a = *((int*)x);
  int b = *((int*)y);
  return a>b ? 1 : a<b ? -1 : 0;
 }*/
 void swap(char*str1, char*str2, int size)
 {
  int i = 0;
  for (i = 0; i < size; i++)//为什么小于size
  {
   char* tmp = 0;
   tmp = str1;
   str1 = str2;
   str2 = tmp;
   str1++;
   str2++;
  }
 }
 int name_compare(const void*str1, const void * str2)
 {
  return strcmp(((struct S *)str1)->name, ((struct S*)str2)->name);
 }
void my_qsort(void * arr, size_t n, size_t size, int* compare(const void* x, const void* y))
{
 int i = 0;
 for (i = 0; i < n - 1; i++)
 {
  int j = 0;
  for (j = 0; j < n - 1 - i; j++)
  {
   if (compare((char*)arr + j, (char*)arr + j + 1)>0)
   {
    swap((char*)arr + j*size, (char*)arr + (j + 1)*size, size);
   }
  }
 }
}
int main()
{
 int i = 0;
 struct S arr[10] = { { "zhangsan", 20 },{ "lisi",15 } };
 /*int arr[10] = { 6, 2, 8, 4, 5, 1, 7, 3, 9,10 };*/
 qsort(arr, sizeof arr / sizeof arr[0], sizeof (struct S), name_compare);
 for (i = 0; i < 10; i++)
 {
  printf("%s ", arr[i].name);
 }
 system("pause");
 return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43647265/article/details/86240654