If you can assume that all values are different, for each value in tab
, its position in the sorted array is the number of values that are strictly lower in tab
:
Here is how it works:
#include <stdio.h>
void getOrder(const int tab[], int n, int pos[]) {
for (int i = 0; i < n; i++) {
int count = 0;
for (int j = 0; j < n; j++)
count += (tab[j] < tab[i]);
pos[i] = count;
}
}
int main() {
int tab[3] = { 5, 1, 4 };
int pos[3];
int n = sizeof(tab) / sizeof(tab[0]);
getOrder(tab, n, pos);
for (int i = 0; i < n; i++)
printf("%d ", pos[i]);
printf("\n");
return 0;
}
If you want different index values for duplicates, you can use 2 loops with slightly fewer tests:
void getOrder(const int tab[], int n, int pos[]) {
for (int i = 0; i < n; i++) {
int j, count = 0;
for (j = 0; j < i; j++)
count += (tab[j] <= tab[i]);
while (++j < n)
count += (tab[j] < tab[i]);
pos[i] = count;
}
}
0
solved Get the ascending order of array element using c language [closed]