30.10.2014 Views

o_195h4n6al16jb186b1b2qs7fgssa.pdf

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

with the key<br />

Remarks: qsortoverwrites the array with the sorted array. The comparison<br />

function is supplied by the user. Inthe following example, the list is<br />

sorted according to the comparison function. This compuses<br />

ascending order.<br />

Example: #include /* for qsort */<br />

#include /* for printf */<br />

#define NUM 7<br />

int comp(const void *e1,const void *e2);<br />

int main(void)<br />

{<br />

int list[NUM] = {35, 47, 63, 25, 93, 16, 52};<br />

int x;<br />

printf("Unsorted List: ");<br />

for (x = 0; x < NUM; x++)<br />

printf("%d ", list[x]);<br />

qsort(list, NUM, sizeof(int), comp);<br />

printf("\n");<br />

printf("Sorted List: ");<br />

for (x = 0; x < NUM; x++)<br />

printf("%d ", list[x]);<br />

}<br />

int comp(const void *e1,const void *e2)<br />

{<br />

const int * a1 = e1;<br />

const int * a2 = e2;<br />

if (*a1 < *a2)<br />

return -1;<br />

else if (*a1 == *a2)<br />

return 0;<br />

else<br />

return 1;<br />

}<br />

Output:<br />

Unsorted List: 35 47 63 25 93 16 52<br />

Sorted List: 16 25 35 47 52 63 93<br />

Ví dụ: # include / * Forprintf * /<br />

# include / * Cho rand, srand * /<br />

int main (void)<br />

{<br />

int x;<br />

srand (7);<br />

for (x = 0; x

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!