代码如下(示例):
void UserMain(void) { int i, j, tmp; s8 raw[] = {9, 10, 10, -2, 8, 3, 2, -5, 1, 0, -8, 3, 2, 8}; // 需要排序的原始数据 int length = sizeof(raw)/sizeof(s8); printf("raw_len: %d", length); s8 *num = (s8 *)tls_mem_alloc(length); // 复制需要排序的数据之后排序 // s8 num[] = {9, 10, 10, 2, -8, 3, 2, 5, 1, 0, 8, -3, -2, -8}; printf("raw:"); for(i = 0;i < length; i++){ num[i] = raw[i]; printf("%d ",num[i]); } printf("\n"); s8 *idx = (s8 *)tls_mem_alloc(length); // 用来保存原数组对应的下标序号 // s8 idx[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}; printf("idx:\n"); for(i = 0;i < length; i++){ idx[i] = i; printf("%d ",idx[i]); } printf("\n"); for(j=0; j<length; j++) { for(i=0; i<length-1-j; i++) { if(num[i] < num[i+1]) { tmp = num[i]; num[i] = num[i+1]; num[i+1] = tmp; tmp = idx[i]; idx[i] = idx[i+1]; idx[i+1] = tmp; } } } printf("num:\n"); for(int i=0; i<length; i++) printf("%d ",num[i]); printf("\n"); printf("idx:\n"); for(int i=0; i<length; i++) printf("%d ",idx[i]); printf("\n"); tls_mem_free(idx); tls_mem_free(num); }
如下:
raw_len: 14 raw:9 10 10 -2 8 3 2 -5 1 0 -8 3 2 8 idx:0 1 2 3 4 5 6 7 8 9 10 11 12 13 num:10 10 9 8 8 3 3 2 2 1 0 -2 -5 -8 idx:1 2 0 4 13 5 11 6 12 8 9 3 7 10