---
title: "Give an example of an algorithm and determine its time complexity in worst, best, and average cases."  
description: "Give an example of an algorithm and determine its time complexity in worst, best, and average cases."  
author: "Revati S Misra"  
published: 2023-04-19  
updated: 2023-04-24  
canonical: https://www.mindstick.com/forum/157927/give-an-example-of-an-algorithm-and-determine-its-time-complexity-in-worst-best-and-average-cases  
category: "algorithm"  
tags: ["algorithm", "Algorithm analysis"]  
reading_time: 2 minutes  

---

# Give an example of an algorithm and determine its time complexity in worst, best, and average cases.

Give an example of an [algorithm and determine](https://www.mindstick.com/forum/157920/provide-an-example-of-an-algorithm-and-determine-its-big-o-notation) its time complexity in worst, best, and average cases.

## Replies

### Reply by Aryan Kumar

Here is an example of an [algorithm](https://www.mindstick.com/blog/119/implementing-cryptography-in-c-sharp-dot-net-by-using-sha1-algorithm) to find the maximum element in an array of integers:

```plaintext
1. Initialize a variable max to be the first element of the array
2. For each element in the array:
     a. If the element is greater than max, set max to be the element
3. Return max
```

The time complexity of this algorithm in the worst, best, and average cases is O(n), where n is the number of elements in the array.

- **Worst case:** The worst case occurs when the maximum element is at the end of the array, or when all elements are in descending order. In this case, the algorithm will iterate through all n elements of the array, so the time complexity will be O(n).
- **Best case:** The best case occurs when the maximum element is at the beginning of the array. In this case, the algorithm will only need to compare the first element to itself, so the time complexity will be O(1).
- **Average case:** The average case occurs when the maximum element is randomly distributed in the array. In this case, the algorithm will need to compare about half of the elements on average, so the time complexity will be O(n/2), which is still O(n).

Overall, this algorithm has a linear time complexity, which means that its running time scales linearly with the size of the input. In other words, as the size of the array grows, the time taken by the algorithm will grow linearly, making it a relatively efficient algorithm for finding the maximum element in an array.


---

Original Source: https://www.mindstick.com/forum/157927/give-an-example-of-an-algorithm-and-determine-its-time-complexity-in-worst-best-and-average-cases

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
