方法
以冒泡排序为例,在对数组元素排序的同时,对下标进行排序。
void sortWithIndex(int* arrValue, int* arrIndex, UINT32 len)
{
int tempArrValue = 0;
int tempArrIndex = 0;
for(int slowIndex = 0; slowIndex < len; slowIndex++)
{
for(int fastIndex = 0; fastIndex < len - slowIndex - 1; fastIndex++)
{
if(arrValue[fastIndex] > arrValue[fastIndex+1])
{
tempArrValue = arrValue[fastIndex];
arrValue[fastIndex] = arrValue[fastIndex+1];
arrValue[fastIndex+1] = tempArrValue;
tempArrIndex = arrIndex[fastIndex];
arrIndex[fastIndex] = arrIndex[fastIndex+1];
arrIndex[fastIndex+1] = tempArrIndex;
}
}
}
return ;
}
测试代码
#include<stdio.h>
#include<stdlib.h>
void sortWithIndex(int* arrValue, int* arrIndex, int len)
{
int tempArrValue = 0;
int tempArrIndex = 0;
for(int slowIndex = 0; slowIndex < len; slowIndex++)
{
for(int fastIndex = 0; fastIndex < len - slowIndex - 1; fastIndex++)
{
if(arrValue[fastIndex] > arrValue[fastIndex+1])
{
tempArrValue = arrValue[fastIndex];
arrValue[fastIndex] = arrValue[fastIndex+1];
arrValue[fastIndex+1] = tempArrValue;
tempArrIndex = arrIndex[fastIndex];
arrIndex[fastIndex] = arrIndex[fastIndex+1];
arrIndex[fastIndex+1] = tempArrIndex;
}
}
}
return ;
}
int main()
{
int temp[10] = {11,5,1,9,15};
int array[4][10] = {0};
for(int i = 0; i < 5; ++i)
{
array[0][i] = temp[i];
array[1][i] = temp[i] + 2;
array[2][i] = temp[i] + 2;
array[3][i] = i;
}
sortWithIndex(&array[2][0], &array[3][0], 5);
printf("\n");
for(int i=0; i<5; i++)
printf("%d ",array[0][i]);
printf("\n\n");
for(int i=0; i<5; i++)
printf("%d ",array[1][i]);
printf("\n\n");
for(int i=0; i<5; i++)
printf("%d ",array[2][i]);
printf("\n\n");
for(int i=0; i<5; i++)
printf("%d ",array[3][i]);
printf("\n\n");
return 0;
}