0
0
Bash-scriptingHow-ToBeginner · 2 min read

Bash Script to Find Second Largest Number in Array

Use a Bash script that iterates through the array, tracks the largest and second largest values, and prints the second largest; for example: arr=(3 5 1 7 4); largest=${arr[0]}; second_largest=-999999; for num in "${arr[@]}"; do if (( num > largest )); then second_largest=$largest; largest=$num; elif (( num > second_largest && num != largest )); then second_largest=$num; fi; done; echo $second_largest.
📋

Examples

Inputarr=(1 2 3 4 5)
Output4
Inputarr=(10 10 9 8 7)
Output9
Inputarr=(5 5 5 5)
Output-999999
🧠

How to Think About It

To find the second largest number, keep track of the largest and second largest values as you check each number in the array. Update these values when you find a bigger number or a number between the largest and second largest. This way, you only need one pass through the array.
📐

Algorithm

1
Initialize largest and second largest with the first element or suitable defaults.
2
Loop through each number in the array.
3
If the current number is greater than largest, update second largest to largest and largest to current number.
4
Else if the current number is greater than second largest and not equal to largest, update second largest.
5
After the loop, return the second largest value.
💻

Code

bash
arr=(3 5 1 7 4)
largest=${arr[0]}
second_largest=-999999
for num in "${arr[@]}"; do
  if (( num > largest )); then
    second_largest=$largest
    largest=$num
  elif (( num > second_largest && num != largest )); then
    second_largest=$num
  fi
done
echo $second_largest
Output
5
🔍

Dry Run

Let's trace the array (3 5 1 7 4) through the code

1

Initialize variables

largest=3, second_largest=-999999

2

Check number 5

5 > 3, so second_largest=3, largest=5

3

Check number 1

1 > 5? No; 1 > second_largest(3)? No; no change

4

Check number 7

7 > 5, so second_largest=5, largest=7

5

Check number 4

4 > 7? No; 4 > second_largest(5)? No; no change

Numberlargestsecond_largest
33-999999
553
153
775
475
💡

Why This Works

Step 1: Track largest and second largest

We keep two variables: largest and second_largest to remember the top two numbers as we scan the array.

Step 2: Update when bigger number found

If a number is bigger than largest, we move the old largest to second_largest and update largest.

Step 3: Update second largest carefully

If a number is between largest and second_largest, we update second_largest only if it is not equal to largest.

🔄

Alternative Approaches

Sort and pick second largest
bash
arr=(3 5 1 7 4)
sorted=($(printf "%s\n" "${arr[@]}" | sort -nr | uniq))
echo ${sorted[1]}
Simple but slower for large arrays due to sorting; also removes duplicates with uniq.
Use Bash associative array to track unique values
bash
declare -A seen
arr=(3 5 1 7 4 5)
for num in "${arr[@]}"; do seen[$num]=1; done
unique=(${!seen[@]})
largest=${unique[0]}
second_largest=-999999
for num in "${unique[@]}"; do
  if (( num > largest )); then
    second_largest=$largest
    largest=$num
  elif (( num > second_largest && num != largest )); then
    second_largest=$num
  fi
done
echo $second_largest
Handles duplicates by filtering unique values first; slightly more complex.

Complexity: O(n) time, O(1) space

Time Complexity

The script loops through the array once, so time complexity is O(n), where n is the number of elements.

Space Complexity

Only a few variables are used regardless of input size, so space complexity is O(1).

Which Approach is Fastest?

The single pass approach is fastest; sorting-based methods are slower at O(n log n) but simpler to write.

ApproachTimeSpaceBest For
Single pass trackingO(n)O(1)Large arrays, best performance
Sorting and pickingO(n log n)O(n)Small arrays, simplicity
Unique filtering + trackingO(n)O(n)Arrays with duplicates
💡
Initialize second largest to a very small number or the first element to handle negative values correctly.
⚠️
Not checking that the second largest is different from the largest, causing incorrect results when duplicates exist.