Thursday, October 19, 2017

Largest and Smallest Element of an Array in C

Calculating largest and smallest element in C is straightforward. All you have to do is scan through the array one element at a time and compare it with current largest or smallest value. Since you scan every element of array, there will be n (number of elements in the array) comparisons. Therefore the running time of this algorithm is $\Theta(n)$.

Calculation of Largest Element
int get_largest(int a[], int n) {
 int i, largest = 0;
 for (i = 0; i < n; i++) {
  if (a[i] > largest) {
   largest = a[i];
  }
 }
 return largest;
}

Calculation of Smallest Element
int get_smallest(int a[], int n) {
 int i, smallest = 2147483647;
 for (i = 0; i < n; i++) {
  if (a[i] < smallest) {
   smallest = a[i];
  }
 }
 return smallest;
}

This code is also available in GitHub.  

No comments:

Post a Comment