寻找最大的索引

时间:2019-08-16 10:15:16

标签: c arrays sorting

我想在C中找到给定数组中最大元素的索引。

在将最大值与所有先前数组的元素进行比较之后,我尝试了插入排序算法来确定数组中的最大数目,但这没有用。

void insertion_array(float array[], int n) //* insertion algorithm*//
{
    int i = 1, j;
    float x;

    for (; i < n; i++) {
        x = array[i];
        j = i - 1;

        while ((j >= 0) && (array[j] > x)) {

            array[j + 1] = array[j];
            j = j - 1;

        }
        array[j + 1] = x;
    }
}

uint8_t Largest_Number_Finder(float arr[], uint8_t n) {
    uint8_t index;
    insertion_array(arr, n);
    for (int i = 0; i < n; i++) {
        if (arr[i] > arr[n - 1]) {
            index = i;

        }
    }
    return index;
}

我期望采用最大的数字索引,但是算法总是给出最后一个元素的索引。我该怎么做才能正确? Edit =您作为重复项导航的是找到最大的元素。我的目标是在数组中找到最大元素的索引。

1 个答案:

答案 0 :(得分:3)

正如注释中提到的“一些程序员伙计”一样,如果您的目的只是查找最大值的索引,则无需实现插入或任何其他算法即可对数组进行排序。

您可能可以创建这样的函数。

int find_max_value(float array[], int length)
{
    // set the value of index 0 as the "current max value"
    float max_value = array[0];
    // the same goes for the index number
    int max_index = 0;

    // go through the array 
    for(int i = 1; i < length; i++)  
    {
        // if the next index's value is greater than the "current max value"
        // update the max_value and max_index
        if(array[i] > max_value)
        {
            max_value = array[i];
            max_index = i;
        }
    }
    return max_index;
}

并尝试使用任何输入值(例如

)调用find_max_value()函数
int result = find_max_value(array1, 10);   // just an example supposing that you have declared an array called "array1" and its length is 10
printf("%d", result);    // see what the return value of the find_max_value() function would be