Largest Element in an Array

We will write a program to find the largest element in an array.

Largest Element in an Array

We are given an array of size n. We need to find out the index of the largest element in the array.

The trick here is to maintain the largest element index. We initialize its value to 0 (to say the first element is the largest), on iteration from second element we verify if the element is greater than current largest element, if so we update the largest element index with that element index.

int getLargest(int[] arr) {
	int maxIdx = 0;
	for (int i = 0; i < arr.length; i++) {
		if (arr[i] > arr[maxIdx]) {
			maxIdx = i;
		}
	}
	return maxIdx;
}

Time complexity of this algorithm is Θ(n), as we are traversing through whole array.