一個C語言的排序問題
2 數組排序
輸入一個數組的值,求出各個值從小到大排序後的次序。
輸入:輸入的第一個數為數組的長度,後面的數為數組中的值,以空格分割,
輸出:各輸入的值按從小到大排列的次序。
sample
input:
4
-3 75 12 -3
output:
1 3 2 1
最佳回答:
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int value;
int pos;
} array_elem;
int array_elem_cmp(const void *x, const void *y) {
int vx = ((array_elem *) x)->value, vy = ((array_elem *) y)->value;
return vx < vy ? -1 : (vx == vy ? 0 : 1);
}
int main() {
int n, i, order, last, *array;
scanf("%d", &n);
array = (int *) malloc(n * sizeof(int));
array_elem *elems = (array_elem *) malloc(n * sizeof(array_elem));
for (i = 0; i < n; ++i) {
scanf("%d", &(elems + i)->value);
(elems + i)->pos = i;
}
qsort(elems, n, sizeof(array_elem), array_elem_cmp);
last = elems[0].value + 1;
for (i = 0, order = 0; i < n; ++i) {
if (elems[i].value != last) {
last = elems[i].value;
++order;
}
array[elems[i].pos] = order;
}
for (i = 0; i < n; ++i) {
printf("%d ", array[i]);
}
free(elems);
free(array);
return 0;
}