C++ Program to Find Smallest Element in Array
int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i];.Examples
How to Think About It
Algorithm
Code
#include <iostream> using namespace std; int main() { int arr[] = {3, 1, 4, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) { min = arr[i]; } } cout << "Smallest element is " << min << endl; return 0; }
Dry Run
Let's trace the array {3, 1, 4, 1, 5} through the code to find the smallest element.
Initialize min
min = 3 (first element)
Compare arr[1] = 1 with min = 3
1 < 3, so min = 1
Compare arr[2] = 4 with min = 1
4 < 1? No, min stays 1
Compare arr[3] = 1 with min = 1
1 < 1? No, min stays 1
Compare arr[4] = 5 with min = 1
5 < 1? No, min stays 1
End of array
Smallest element found is 1
| Index | Current Element | Current Min |
|---|---|---|
| 0 | 3 | 3 |
| 1 | 1 | 1 |
| 2 | 4 | 1 |
| 3 | 1 | 1 |
| 4 | 5 | 1 |
Why This Works
Step 1: Start with first element
We assume the first element is the smallest to have a starting point for comparison.
Step 2: Compare each element
We check each element using if (arr[i] < min) to find if there is a smaller value.
Step 3: Update smallest value
When a smaller element is found, we update min to keep track of the smallest number.
Step 4: Result after loop
After checking all elements, min holds the smallest element in the array.
Alternative Approaches
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {3, 1, 4, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); int min = *min_element(arr, arr + n); cout << "Smallest element is " << min << endl; return 0; }
#include <iostream> #include <algorithm> using namespace std; int main() { int arr[] = {3, 1, 4, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); sort(arr, arr + n); cout << "Smallest element is " << arr[0] << endl; return 0; }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so the time grows linearly with the array size, making it O(n).
Space Complexity
Only a few variables are used regardless of input size, so space complexity is O(1).
Which Approach is Fastest?
The simple loop approach is fastest for just finding the smallest element. Using sorting is slower (O(n log n)), and std::min_element is optimized but similar to the loop.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Simple loop | O(n) | O(1) | Finding smallest element quickly |
| std::min_element | O(n) | O(1) | Cleaner code with standard library |
| Sorting array | O(n log n) | O(1) | When sorted array is also needed |