Here is a naive implementation in simple C. Remove fprintf(stderr, ... after testing. ITEM can be anything if the comparison function is possible. Otherwise: use pointers for ITEM (and maybe add an extra argument sizeofelem, ala qsort)
#include <stdio.h> #include <string.h> typedef int ITEM; int item_cmp(ITEM one, ITEM two); unsigned one_bubble( ITEM *arr, unsigned cnt, unsigned hot , int (*cmp)(ITEM,ITEM) ); int item_cmp(ITEM one, ITEM two) { fprintf(stderr,"Cmp= %u to %u: %d\n", one, two, one-two); if (one > two) return 1; else if (one < two) return -1; else return 0; } unsigned one_bubble( ITEM *arr, unsigned cnt, unsigned hot , int (*cmp)(ITEM,ITEM) ) { unsigned goal = cnt; int diff; ITEM temp; /* hot element should move to the left */ if (hot > 0 && (diff=cmp( arr[hot-1], arr[hot])) > 0) { /* Find place to insert (this could be a binary search) */ for (goal= hot; goal-- > 0; ) { diff=cmp( arr[goal], arr[hot]); if (diff <= 0) break; } goal++; fprintf(stderr,"Move %u LEFT to %u\n", hot, goal); if (goal==hot) return hot; temp = arr[hot]; /* shift right */ fprintf(stderr,"memmove(%u,%u,%u)\n", goal+1, goal, (hot-goal) ); memmove(arr+goal+1, arr+goal, (hot-goal) *sizeof temp); arr[goal] = temp; return goal; /* new position */ } /* hot element should move to the right */ else if (hot < cnt-1 && (diff=cmp( arr[hot], arr[hot+1])) > 0) { /* Find place to insert (this could be a binary search) */ for (goal= hot+1; goal < cnt; goal++ ) { diff=cmp( arr[hot], arr[goal]); if (diff <= 0) break; } goal--; fprintf(stderr,"Move %u RIGHT to %u\n", hot, goal); if (goal==hot) return hot; temp = arr[hot]; /* shift left */ fprintf(stderr,"memmove(%u,%u,%u)\n", hot, hot+1, (goal-hot) ); memmove(arr+hot, arr+hot+1, (goal-hot) *sizeof temp); arr[goal] = temp; return goal; /* new position */ } fprintf(stderr,"Diff=%d Move %u Not to %u\n", diff, hot, goal); return hot; } ITEM array[10] = { 1,10,2,3,4,5,6,7,8,9,}; #define HOT_POS 1 int main(void) { unsigned idx; idx = one_bubble(array, 10, HOT_POS, item_cmp); printf("%u-> %u\n", HOT_POS, idx ); for (idx = 0; idx < 10; idx++) { printf("%u: %u\n", idx, array[idx] ); } return 0; }