查找一组数中的最大、最小值
/**
* 查找一组数中的最大数
* @param nums 数组指针
* @param step sizeof(type)
* @param n 该组数中有几个数
* @return 未找到返回-1,找到返回该数的索引
*/
int findMax(const void *nums, int step, int n)
{
int index = -1;
uint32_t i = 0;
uint32_t maxVal = 0;
uint8_t *p = (uint8_t *)nums;
uint32_t tmp = 0;
if(step == 1)
maxVal = *((uint8_t *)(p));
else if(step == 2)
maxVal = *((uint16_t *)(p));
else if(step == 4)
maxVal = *((uint32_t *)(p));
else
return index;
for(i = 0; i != n; i++)
{
if(step == 1)
tmp = *((uint8_t *)(p + i * step));
else if(step == 2)
tmp = *((uint16_t *)(p + i * step));
else if(step == 4)
tmp = *((uint32_t *)(p + i * step));
else
return -1;
if(maxVal < tmp)
{
maxVal = tmp;
index = i;
}
}
return index;
}
/**
* 查找到一组数中的最小数
* @param nums 数组指针
* @param step sizeof(type)
* @param n 该数组有几个数
* @return 未找到返回-1,找到返回该值索引
*/
int findMin(const void *nums, int step, int n)
{
int index = -1;
uint32_t i = 0;
uint32_t minVal = 0;
uint8_t *p = (uint8_t *)nums;
uint32_t tmp = 0;
if(step == 1)
minVal = *((uint8_t *)(p));
else if(step == 2)
minVal = *((uint16_t *)(p));
else if(step == 4)
minVal = *((uint32_t *)(p));
else
return index;
for(i = 0; i != n; i++)
{
if(step == 1)
tmp = *((uint8_t *)(p + i * step));
else if(step == 2)
tmp = *((uint16_t *)(p + i * step));
else if(step == 4)
tmp = *((uint32_t *)(p + i * step));
else
return -1;
if(minVal >= tmp)
{
minVal = tmp;
index = i;
}
}
return index;
}