备忘qsort函数的使用

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

#define NUM 40

void fillarray (double ar[],int n);
void showarray (const void *pl, int n);
int mycomp (const void *pl, const void *p2);

int main (void)
{
 double vals[NUM];
 fillarray (vals, NUM);
 puts ("Random list: ");
 showarray (vals, NUM);
 qsort (vals, NUM, sizeof (double), mycomp);
 puts ("/nSorted list: ");
 showarray (vals, NUM);
 
 return 0;
}

void fillarray (double ar[], int n)
{
 int index;
 for (index = 0; index < n; index++)
  ar[index] = (double) rand ()/((double) rand () +0.1);
}

void showarray (const double ar[], int n)
{
 int index;
 
 for (index = 0; index < n; index++)
 {
  printf ("%9.4f ",ar[index]);
  if (index % 6 == 5)
   putchar ('/n');
 }
 if (index % 6 != 0)
  putchar ('/n');
}

int mycomp (const void *p1, const void *p2)
{
 const double *a1 = (const double *)p1;
 const double *a2 = (const double *)p2;
 
 if (*a1 < *a2)
  return -1;
 else if (*a1 == *a2)
  return 0;
 else
  return 1;
}

阅读更多
文章标签: random include list
上一篇利用fgets代替gets
下一篇memcpy和memmove
想对作者说点什么? 我来说一句

qsort 用法详解

qsort

hurmishine hurmishine

2015-11-16 19:11:05

阅读数:1734

没有更多推荐了,返回首页

关闭
关闭