Sort an integer array: Difference between revisions

(→‎{{header|UNIX Shell}}: Show easier way, without real arrays. Remove 'tr' solution because it does not handle tabs, multiple spaces and such.)
Line 126:
 
=={{header|C}}==
<lang c>#include <stdlib.h> /* qsort() */
{{works with|gcc|4.0.1}}
<lang c>#include <stdlibstdio.h> /* printf() */
 
int intcmp(const void *aaa, const void *bbb)
{
return *(const int *)a -= aa, *(constb int= *)bbb;
return (*a < *b) ? -1 : (*a > *b);
}
 
Line 138 ⟶ 139:
int nums[5] = {2,4,3,1,2};
qsort(nums, 5, sizeof(int), intcmp);
printf("result: %d %d %d %d %d\n",
nums[0], nums[1], nums[2], nums[3], nums[4]);
return 0;
}</lang>
 
''Caution:'' An older version of <tt>intcmp()</tt> did <tt>return *a - *b</tt>. This was wrong because the subtraction can overflow. Suppose that <tt>*a = 2000000000</tt> and <tt>*b = -2000000000</tt> on a machine with 32-bit <tt>int</tt>. The subtraction <tt>*a - *b</tt> would overflow to <tt>-294967296</tt>, and <tt>intcmp()</tt> would believe <tt>*a < *b</tt>, but the correct answer is <tt>*a > *b</tt>.
 
=={{header|C++}}==
Anonymous user