QUESTION #027

Sort Four Numbers in Descending Order

Easy

📋 Problem Statement

Arrange the given 4 numbers in descending order (largest to smallest).

🎯 Sorting Technique: Elimination Logic

Instead of comparing all pairs, this problem uses a clever elimination strategy:

  1. Find the largest number (max1)
  2. Find the smallest number (max4)
  3. Identify the two middle numbers by eliminating max1 and max4

This reduces the problem complexity significantly!

🔑 Key Concepts

  • Elimination Logic: Identify what something is NOT, rather than what it IS
  • Nested min/max: Finding extremes using nested function calls
  • Conditional Chains: Using if-else to check multiple conditions
  • Descending Order: Largest → Smallest (opposite of ascending)
Elimination-Based Sorting Strategy
Input: a=2, b=0, c=4, d=1

Step 1: Find max1 (Largest)
        max(max(2,0), max(4,1))
        max(2, 4) = 4  ✓

Step 2: Find max4 (Smallest)
        min(min(2,0), min(4,1))
        min(0, 1) = 0  ✓

Step 3: Find max2 (First Middle)
        Check each: Is it NOT max1 AND NOT max4?
        a=2: NOT 4 AND NOT 0? ✓ → max2 = 2

Step 4: Find max3 (Second Middle)
        Check each: Is it NOT max1, max4, AND max2?
        d=1: NOT 4, 0, or 2? ✓ → max3 = 1

Output: 4 > 2 > 1 > 0

📥 Input Format

Accept four integer as a input

📤 Output Format

Print the output as "max1 > max2 > max3 > max4"

💡 Examples

Example 1:
Input: 2 0 4 1
Output: 4 > 2 > 1 > 0
Step-by-step:
• Values: a=2, b=0, c=4, d=1
• max1 (largest): max(max(2,0), max(4,1)) = 4
• max4 (smallest): min(min(2,0), min(4,1)) = 0
• max2 (first middle): a=2 is NOT 4 and NOT 0 → max2 = 2
• max3 (second middle): d=1 is NOT 4, 0, or 2 → max3 = 1
Result: 4 > 2 > 1 > 0
Example 2:
Input: 1 2 3 4
Output: 4 > 3 > 2 > 1
Step-by-step:
• Already in ascending order, need to reverse
• max1 = 4, max4 = 1
• max2 = 3, max3 = 2
Result: Perfect descending order
Example 3 (All Equal):
Input: 5 5 5 5
Output: 5 > 5 > 5 > 5
Analysis:
• All values are identical
• max1 = max4 = 5
• Elimination logic still works correctly
Result: 5 > 5 > 5 > 5
Example 4 (Negative Numbers):
Input: -5 -10 -2 -8
Output: -2 > -5 > -8 > -10
Analysis:
• Values: a=-5, b=-10, c=-2, d=-8
• max1 (largest/least negative): -2
• max4 (smallest/most negative): -10
• Middle values: -5 and -8
Result: -2 > -5 > -8 > -10
Example 5 (Already Sorted Descending):
Input: 40 30 20 10
Output: 40 > 30 > 20 > 10
Analysis:
• Already in descending order
• Algorithm correctly maintains the order
Result: 40 > 30 > 20 > 10

⚠️ Constraints

-10^15 <= INPUT <= 10^15

✅ Solution

#include <iostream>
#include <algorithm> // for min() and max()
using namespace std;

int main() {
    long long a, b, c, d;
    cin >> a >> b >> c >> d;

    long long max1 = max(max(a, b), max(c, d)); // largest
    long long max4 = min(min(a, b), min(c, d)); // smallest

    // For middle two, pick the remaining numbers
    long long max2, max3;

    // Assign remaining numbers
    if ((a != max1 && a != max4)) max2 = a;
    else if ((b != max1 && b != max4)) max2 = b;
    else if ((c != max1 && c != max4)) max2 = c;
    else max2 = d;

    if ((a != max1 && a != max4 && a != max2)) max3 = a;
    else if ((b != max1 && b != max4 && b != max2)) max3 = b;
    else if ((c != max1 && c != max4 && c != max2)) max3 = c;
    else max3 = d;

    cout << max1 << " > " << max2 << " > " << max3 << " > " << max4 << endl;

    return 0;
}

🧠 Understanding the Elimination Logic

Why This Approach is Clever:

// Traditional approach: Compare all pairs (6 comparisons)
// a vs b, a vs c, a vs d, b vs c, b vs d, c vs d

// Elimination approach: Find extremes, then exclude them
// Step 1: Find largest (2 comparisons in nested max)
// Step 2: Find smallest (2 comparisons in nested min)
// Step 3: Find middle values by elimination

// This is more intuitive and easier to understand!

How Elimination Works:

// Given: a=2, b=0, c=4, d=1
// max1 = 4, max4 = 0

// Finding max2:
if ((a != max1 && a != max4))  // Is a NOT 4 AND NOT 0?
    max2 = a;                        // Yes! a=2 ✓

// Finding max3:
if ((a != max1 && a != max4 && a != max2))  // Is a NOT 4, 0, or 2?
    max3 = a;                                     // No, a=2 is max2
else if ((b != max1 && b != max4 && b != max2)) // Is b NOT 4, 0, or 2?
    max3 = b;                                     // No, b=0 is max4
else if ((c != max1 && c != max4 && c != max2)) // Is c NOT 4, 0, or 2?
    max3 = c;                                     // No, c=4 is max1
else
    max3 = d;                                     // Yes! d=1 ✓

🔢 Understanding Nested min() and max()

Finding the Largest of Four Numbers:

// max() only works with 2 arguments at a time
// To find max of 4 numbers: nest the calls

max1 = max(max(a, b), max(c, d));
       ↓
       max(  max(a,b)  ,  max(c,d)  )
           ↓              ↓
       max of first   max of second
       two numbers    two numbers
           ↓
       Final: max of both results

// Example: a=2, b=0, c=4, d=1
max1 = max(max(2, 0), max(4, 1))
     = max(2, 4)
     = 4

Finding the Smallest of Four Numbers:

// Same logic with min()
max4 = min(min(a, b), min(c, d));

// Example: a=2, b=0, c=4, d=1
max4 = min(min(2, 0), min(4, 1))
     = min(0, 1)
     = 0

Why Variable Names are max1, max2, max3, max4:

  • max1: 1st position in descending order (largest)
  • max2: 2nd position in descending order (2nd largest)
  • max3: 3rd position in descending order (3rd largest)
  • max4: 4th position in descending order (smallest)

🔍 Handling Edge Cases

Case 1: All Numbers Equal

// Input: 5 5 5 5
max1 = 5  // largest
max4 = 5  // smallest (same as largest!)

// Finding max2: none of a,b,c,d satisfy (x != 5 && x != 5)
// Falls through to else: max2 = d = 5 ✓

// Finding max3: similarly falls through to else: max3 = 5 ✓

// Output: 5 > 5 > 5 > 5

Case 2: Two Numbers Equal

// Input: 3 3 1 5
max1 = 5
max4 = 1

// Both a and b are 3 (neither is max1 or max4)
// First if catches: max2 = a = 3
// Second if-else finds: max3 = b = 3

// Output: 5 > 3 > 3 > 1 ✓

Case 3: Negative Numbers

// Input: -5 -10 -2 -8
max1 = max(max(-5, -10), max(-2, -8))
     = max(-5, -2)
     = -2  // least negative = largest ✓

max4 = min(min(-5, -10), min(-2, -8))
     = min(-10, -8)
     = -10 // most negative = smallest ✓

// Output: -2 > -5 > -8 > -10

🔑 Key Concepts Learned

  • Elimination Strategy: Finding values by excluding what they're NOT
  • Nested Functions: Using function results as arguments to other functions
  • Descending Order: Arranging from largest to smallest
  • Compound Conditions: Using && to check multiple conditions
  • If-Else Chains: Sequential checking until a condition matches
  • Algorithm Library: Using min() and max() from <algorithm>

🔄 Alternative Sorting Approaches

Method Pros Cons
Elimination Logic
(Current)
• Intuitive
• Educational
• Good for learning
• More lines of code
• Manual logic
Array + std::sort() • Shortest code
• Professional
• Scalable
• Uses advanced concepts
• Less educational
Bubble Sort • Classic algorithm
• Educational
• Overkill for 4 numbers
• More complex
Manual If-Else • No functions needed
• Complete control
• Many comparisons
• Error-prone
• Hard to maintain
Initializer List • Modern C++
• Clean syntax
• Doesn't give individual sorted values
• Only max/min

Using std::sort() (Professional Approach):

#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    long long arr[4];
    for(int i=0; i<4; i++) cin >> arr[i];
    
    sort(arr, arr+4, greater<long long>()); // descending
    
    cout << arr[0] << " > " << arr[1] << " > " 
         << arr[2] << " > " << arr[3] << endl;
    
    return 0;
}

↕️ Ascending vs Descending Order

Aspect Ascending Order Descending Order
Direction Smallest → Largest Largest → Smallest
Symbol < (less than) > (greater than)
Example 1 < 2 < 3 < 4 4 > 3 > 2 > 1
First Position Minimum value Maximum value
Last Position Maximum value Minimum value
Common Use Default sorting
Finding minimums
Rankings
Top scores
Leaderboards

🌍 Real-world Applications

  • Leaderboards: Ranking players by score (highest first)
  • Product Sorting: "Price: High to Low" in e-commerce
  • News Feeds: Most recent posts first (descending by timestamp)
  • Stock Markets: Top gainers/losers (descending by percentage)
  • Search Results: Most relevant results first (descending by relevance score)
  • Grade Reports: Highest performing students first
  • Sales Reports: Best-selling products at the top
  • Ranking Systems: Any system that needs "best first" ordering

🎯 What You'll Learn

  • Understanding elimination-based sorting strategies
  • Working with nested min() and max() functions
  • Implementing descending order sorting
  • Handling edge cases (equal values, negatives)
  • Using compound logical conditions (&&)
  • Building if-else chains for value assignment
  • Understanding when to use elimination vs comparison
  • Comparing manual logic with library functions

💪 Extension Challenges

  • Level 1: Modify to sort in ascending order instead
  • Level 2: Sort 5 numbers using the same elimination technique
  • Level 3: Implement using only if-else (no min/max functions)
  • Level 4: Rewrite using arrays and std::sort()
  • Level 5: Add median calculation (average of max2 and max3)
  • Level 6: Implement bubble sort for 4 numbers
  • Level 7: Create a function that sorts N numbers using elimination
  • Bonus: Compare execution time of different sorting methods

💡 Practice Tips

  • Trace by Hand: Write out the values and elimination steps on paper
  • Test Edge Cases: All equal, two equal, negatives, zeros
  • Understand Nesting: Draw diagrams showing how nested max/min work
  • Compare Methods: Implement using different approaches and compare
  • Use Debugger: Step through to see how max2 and max3 are found
  • Modify Output: Try different separators (commas, arrows, etc.)
  • Experiment: What happens if you swap max1 and max4 in output?
  • Learn std::sort(): Research how to use the standard sorting algorithm