How can you remove the largest value from an array in C language?

To remove the maximum value from an array, firstly locate the index of the maximum value, then shift the elements following that index one position backwards. Here is an example code:

#include <stdio.h>

void deleteMax(int arr[], int size) {
    int maxIndex = 0; // 初始最大值索引为第一个元素的索引
    int i;
    
    // 找到最大值的索引
    for (i = 1; i < size; i++) {
        if (arr[i] > arr[maxIndex]) {
            maxIndex = i;
        }
    }
    
    // 将最大值后面的元素依次向前移动一个位置
    for (i = maxIndex; i < size - 1; i++) {
        arr[i] = arr[i+1];
    }
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    int i;
    
    printf("原始数组:");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    deleteMax(arr, size);
    size--; // 删除最大值后,数组长度减1
    
    printf("删除最大值后的数组:");
    for (i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    return 0;
}

Result of execution:

原始数组:1 2 3 4 5 
删除最大值后的数组:1 2 3 4 
bannerAds