How to Find the Maximum Value in an Unsorted Array: C

Samantha Balgobin
2 min readNov 10, 2020

--

To find the maximum value in an unsorted array, we have to search linearly by checking each element and keeping track of the position the maximum is found at so far. We then return the element at the position of the maximum. The time complexity of this algorithm is O(n). It is not possible to find the maximum value without checking each element in the array given that it is unsorted.

We will be using a loop to traverse an array of integers. We first create a variable to store the maximum value and initialize it to the first element of the array to be traversed.

int nums[] = {10, 2, 12, 4, 8};// Create a variable called largest and set it equal to the first element of the arrayint maximum = nums[0];

We then find the number of elements in the array and store that quantity in a variable to use for our loop. If we divide the size of the array (20 bytes) by the size of an int (4 bytes), the output should be equal to 5.

// Find the length of the arrayint length = sizeof(nums) / sizeof(int);

Using a loop, we traverse each element of the array, incrementing the counter by one. In each iteration, we compare the value of maximum to the element of the array at the i-th position. If the value of the i-th element of the array is greater than the maximum, we set the maximum equal to the value of that element.

// Compare the value at every n-1 element to see if it is larger than the maximum. If so, set maximum to that number.for (int i = 1; i < length; i++){    if (maximum < nums[i])    {        maximum = nums[i];    }}

At the end of the loop, we will be left with the maximum value. Here is the function all together:

--

--

Samantha Balgobin
Samantha Balgobin

Written by Samantha Balgobin

Just another human being on a journey.

No responses yet