利用C库函数完成的排序

<textarea cols="50" rows="15" name="code" class="cpp">#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; /* **该函数有qsort调用,用于比较整型值 */ int compare_integers(void const *a,void const *b) { register int const *pa = a; register int const *pb = b; return *pa &gt; *pb? 1:*pa &lt; *pb ? -1:0; } int main() { int *array; int n_values; int i; /*观察共有多少个值*/ printf(&quot;How many values are there?&quot;); if(scanf(&quot;%d&quot;,&amp;n_values) != 1 || n_values &lt;= 0) { printf(&quot;Illegal number of values./n&quot;); exit(EXIT_FAILURE); } /*分配内存,用于存储这些值*/ array = malloc(n_values * sizeof(int)); if(array == NULL){ printf(&quot;Cant't get memory for that many values.&quot;); exit(EXIT_FAILURE); } /*读取数据*/ for(i = 0;i &lt; n_values;i+=1){ printf(&quot;?&quot;); if(scanf(&quot;%d&quot;,array + i) != 1){ printf(&quot;Error reading value #%d/n&quot;,i); free(array); exit(EXIT_FAILURE); } } /*对这些值进行排序*/ qsort(array,n_values,sizeof(int),compare_integers); /*输出排序结果*/ for(i = 0;i &lt; n_values;i += 1) printf(&quot;%d/n&quot;,array[i]); /*释放内存*/ free(array); return EXIT_SUCCESS; } </textarea>

你可能感兴趣的:(利用C库函数完成的排序)