pete
3/19/2011 3:29:00 AM
cerr wrote:
>
> Hi There,
>
> I have no problem doing a bubble sort in an array but what if i need
> to keep an identifier that is linked to the value so i always know
> which values is where?
> I have a little array with three "offset" elements and i would like to
> sort them so that the smallest offset is at position 0. I can do that
> with an array, n.p.:
> // Bubble sort offset times
> for (ctr=0;ctr<OFFSET_ARR_SZ;ctr++) {
> if (iarray[ctr] > iarray[ctr+1]) {
> //Here a swap is needed
> temp=iarray[ctr+1];
> iarray[ctr+1]=iarray[ctr];
> iarray[ctr]=temp;
> }
> }
> but once they're sorted and i want to take action i need to know what
> action to take after the first offset i.e. i need to keep some kind of
> identifier. I am aware that I could just sort after applying some kind
> of binary mask to keep an id in my value... but i imagine there's a
> more transparent way e.g. by sorting values in a structure...?
> Recommendations and hints appreciated!
> Thanks!
/* BEGIN new.c output */
Before sorting by data:
array[0] data is 0, type is SYNC
array[1] data is 500, type is LPR
array[2] data is 200, type is OVR
After sorting by data:
array[0] data is 0, type is SYNC
array[1] data is 200, type is OVR
array[2] data is 500, type is LPR
/* END new.c output */
/* BEGIN new.c */
#include <stdio.h>
#define E_TYPE struct i e_type
#define MOV(A, B) ((void)(*(A) = *(B)))
#define GT(A, B) ((A) -> data > (B) -> data)
#define NMEMB(A) (sizeof (A) / sizeof *(A))
typedef E_TYPE;
struct i {
unsigned data;
char *type;
};
void sisort(e_type *array, size_t nmemb);
int
main(void)
{
unsigned index;
struct i array[] = {
{ 0, "SYNC"},
{500, "LPR" },
{200, "OVR" }
};
puts("/* BEGIN new.c output */\n");
puts("Before sorting by data:");
for (index = 0; index != NMEMB(array); ++index) {
printf("array[%u] data is %3u, type is %s\n",
index, array[index].data, array[index].type);
}
sisort(array, NMEMB(array));
puts("\nAfter sorting by data:");
for (index = 0; index != NMEMB(array); ++index) {
printf("array[%u] data is %3u, type is %s\n",
index, array[index].data, array[index].type);
}
puts("\n/* END new.c output */");
return 0;
}
void
sisort(e_type *array, size_t nmemb)
{
e_type *base, *low, *high, temp;
if (nmemb-- > 1) {
base = array;
do {
low = array++;
if (GT(low, array)) {
high = array;
MOV(&temp, high);
do {
MOV(high, low);
if (--high == base) {
break;
}
--low;
} while (GT(low, &temp));
MOV(high, &temp);
}
} while (--nmemb != 0);
}
}
/* END new.c */
--
pete