mirror of
https://git.FreeBSD.org/src.git
synced 2024-12-24 11:29:10 +00:00
Various improvements to the qsort(3) usage example:
- Remove unused #include. - Do not cast away const. - Use the canonical idiom to compare two numbers. - Use proper type for sizes, i.e. size_t instead of int. - Correct indentation. - Simplify printf("\n") to puts(""). - Use return instead of exit() in main(). Submitted by: Christoph Mallon, christoph.mallon at gmx.de Approved by: gjb (mentor) Reviewed by: stefanf MFC after: 1 week
This commit is contained in:
parent
6a8f90edf5
commit
302318d549
Notes:
svn2git
2020-12-20 02:59:44 +00:00
svn path=/head/; revision=247050
@ -220,7 +220,6 @@ and then prints the sorted array to standard output is:
|
|||||||
.Bd -literal
|
.Bd -literal
|
||||||
#include <stdio.h>
|
#include <stdio.h>
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#include <string.h>
|
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Custom comparison function that can compare 'int' values through pointers
|
* Custom comparison function that can compare 'int' values through pointers
|
||||||
@ -229,15 +228,10 @@ and then prints the sorted array to standard output is:
|
|||||||
static int
|
static int
|
||||||
int_compare(const void *p1, const void *p2)
|
int_compare(const void *p1, const void *p2)
|
||||||
{
|
{
|
||||||
int *left = (int *)p1;
|
int left = *(const int *)p1;
|
||||||
int *right = (int *)p2;
|
int right = *(const int *)p2;
|
||||||
|
|
||||||
if (*left < *right)
|
return ((left > right) - (left < right));
|
||||||
return (-1);
|
|
||||||
else if (*left > *right)
|
|
||||||
return (1);
|
|
||||||
else
|
|
||||||
return (0);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
@ -247,14 +241,14 @@ int
|
|||||||
main(void)
|
main(void)
|
||||||
{
|
{
|
||||||
int int_array[] = { 4, 5, 9, 3, 0, 1, 7, 2, 8, 6 };
|
int int_array[] = { 4, 5, 9, 3, 0, 1, 7, 2, 8, 6 };
|
||||||
const int array_size = sizeof(int_array) / sizeof(int_array[0]);
|
const size_t array_size = sizeof(int_array) / sizeof(int_array[0]);
|
||||||
int k;
|
size_t k;
|
||||||
|
|
||||||
qsort(&int_array, array_size, sizeof(int), int_compare);
|
qsort(&int_array, array_size, sizeof(int_array[0]), int_compare);
|
||||||
for (k = 0; k < array_size; k++)
|
for (k = 0; k < array_size; k++)
|
||||||
printf(" %d", int_array[k]);
|
printf(" %d", int_array[k]);
|
||||||
printf("\\n");
|
puts("");
|
||||||
exit(EXIT_SUCCESS);
|
return (EXIT_SUCCESS);
|
||||||
}
|
}
|
||||||
.Ed
|
.Ed
|
||||||
.Sh ERRORS
|
.Sh ERRORS
|
||||||
|
Loading…
Reference in New Issue
Block a user