C# Program to Find Smallest Element in Array
int min = arr[0]; foreach (int num in arr) { if (num < min) min = num; }.Examples
How to Think About It
Algorithm
Code
using System; class Program { static void Main() { int[] arr = {5, 3, 8, 1, 4}; int min = arr[0]; foreach (int num in arr) { if (num < min) { min = num; } } Console.WriteLine(min); } }
Dry Run
Let's trace the array [5, 3, 8, 1, 4] through the code to find the smallest number.
Initialize min
min = 5 (first element)
Compare with 3
3 < 5, so min = 3
Compare with 8
8 < 3? No, min stays 3
Compare with 1
1 < 3, so min = 1
Compare with 4
4 < 1? No, min stays 1
Result
Smallest number is 1
| Current Number | Current Min |
|---|---|
| 5 | 5 |
| 3 | 3 |
| 8 | 3 |
| 1 | 1 |
| 4 | 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 number using if (num < min) to find if there's a smaller one.
Step 3: Update smallest value
When a smaller number is found, we update min to that number.
Step 4: Return smallest
After checking all elements, the min holds the smallest number in the array.
Alternative Approaches
using System; class Program { static void Main() { int[] arr = {5, 3, 8, 1, 4}; Array.Sort(arr); Console.WriteLine(arr[0]); } }
using System; using System.Linq; class Program { static void Main() { int[] arr = {5, 3, 8, 1, 4}; int min = arr.Min(); Console.WriteLine(min); } }
Complexity: O(n) time, O(1) space
Time Complexity
The program checks each element once, so time grows linearly with 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 loop method and LINQ Min() both run in O(n), but sorting is slower at O(n log n) and changes the array.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Loop with comparison | O(n) | O(1) | Fastest, no extra memory, original array unchanged |
| Array.Sort() | O(n log n) | O(1) | Simple but slower and modifies array |
| LINQ Min() | O(n) | O(1) | Clean code, requires LINQ, original array unchanged |