# Median of Two Sorted Arrays - C++ Implementation

This project provides a comprehensive C++ implementation for finding the median of two sorted arrays, featuring both optimal binary search and educational merge-based approaches.

## 🚀 Features

- **Two Algorithm Implementations**:
  - Binary Search Approach: O(log(min(m,n))) time complexity
  - Merge Approach: O(m+n) time complexity (educational)
- **Comprehensive Testing Suite**: Automated tests with edge cases
- **Interactive Demo**: User-friendly interface for custom inputs
- **Random Stress Testing**: Validates correctness with random test cases
- **Professional Code Structure**: Following C++ best practices and style guidelines
- **Memory Safe**: Proper error handling and input validation

## 📁 Project Structure

```
├── MedianFinder.h              # Header file with class declarations
├── MedianFinder.cc             # Implementation file
├── main.cpp                    # Main program with menu interface
├── median_of_two_sorted_arrays.cpp  # Standalone complete example
├── Makefile_median             # Build configuration
└── README_median.md            # This documentation
```

## 🛠️ Building the Project

### Prerequisites
- C++17 compatible compiler (GCC 7+, Clang 5+, MSVC 2017+)
- Make (optional, for using Makefile)

### Compilation Options

#### Using Makefile (Recommended)
```bash
# Build main program
make -f Makefile_median

# Build standalone version
make -f Makefile_median standalone

# Build with debug information
make -f Makefile_median debug

# Build optimized release
make -f Makefile_median release
```

#### Manual Compilation
```bash
# Main program
g++ -std=c++17 -Wall -Wextra -O2 main.cpp MedianFinder.cc -o median_finder

# Standalone version
g++ -std=c++17 -Wall -Wextra -O2 median_of_two_sorted_arrays.cpp -o median_standalone
```

## 🎯 Usage

### Running the Main Program
```bash
./median_finder
```

The program provides a menu-driven interface with the following options:
1. **Run automated test suite** - Comprehensive testing with predefined cases
2. **Run interactive demo** - Enter your own arrays
3. **Run random stress tests** - Validate with randomly generated test cases
4. **Show algorithm complexity information** - Display time/space complexity details
5. **Exit** - Quit the program

### Running the Standalone Version
```bash
./median_standalone
```

### Example Usage
```cpp
#include "MedianFinder.h"
#include <vector>

int main() {
    std::vector<int> nums1 = {1, 3};
    std::vector<int> nums2 = {2};
    
    double median = MedianFinder::FindMedianSortedArrays(nums1, nums2);
    std::cout << "Median: " << median << std::endl;  // Output: 2
    
    return 0;
}
```

## 🧮 Algorithm Details

### Binary Search Approach (Optimal)
- **Time Complexity**: O(log(min(m,n)))
- **Space Complexity**: O(1)
- **Strategy**: Partitions arrays to find the correct median position using binary search
- **Best for**: Production use, large datasets

### Merge Approach (Educational)
- **Time Complexity**: O(m+n)
- **Space Complexity**: O(1)
- **Strategy**: Simulates merging until reaching median position(s)
- **Best for**: Understanding the problem, smaller datasets

## 🧪 Testing

### Automated Test Cases
The program includes comprehensive test cases covering:
- Basic examples with odd/even total lengths
- Empty arrays
- Arrays of different sizes
- Non-overlapping arrays
- Identical arrays
- Negative numbers
- Large value differences
- Edge cases

### Running Tests
```bash
# Run all tests
make -f Makefile_median test

# Memory leak detection (requires valgrind)
make -f Makefile_median memcheck

# Static analysis (requires cppcheck)
make -f Makefile_median analyze
```

## 📊 Performance Characteristics

| Array Sizes | Binary Search | Merge Approach |
|-------------|---------------|----------------|
| 1000, 1000  | ~10 operations | ~1000 operations |
| 10000, 10000| ~14 operations | ~10000 operations |
| 1M, 1M      | ~20 operations | ~1M operations |

## 🔧 Development Tools

### Available Make Targets
```bash
make -f Makefile_median help  # Show all available targets
make -f Makefile_median clean # Clean build artifacts
make -f Makefile_median format # Format code (requires clang-format)
```

### Code Style
The implementation follows established C++ coding standards:
- Class names: `PascalCase`
- Method names: `PascalCase`
- Variables: `snake_case` (local), `mPascalCase` (member)
- Constants: `ALL_CAPS`
- File extensions: `.h` for headers, `.cc` for implementation

## 🚨 Error Handling

The implementation includes robust error handling for:
- Non-sorted input arrays
- Invalid input validation
- Empty array combinations
- Numerical overflow protection
- Memory allocation failures

## 📝 Example Test Cases

```cpp
// Test Case 1: Basic example
nums1 = {1, 3}, nums2 = {2} → median = 2.0

// Test Case 2: Even total length
nums1 = {1, 2}, nums2 = {3, 4} → median = 2.5

// Test Case 3: One empty array
nums1 = {}, nums2 = {1} → median = 1.0

// Test Case 4: No overlap
nums1 = {1, 2, 3}, nums2 = {4, 5, 6} → median = 3.5
```

## 🤝 Contributing

1. Follow the existing code style and naming conventions
2. Add appropriate test cases for new features
3. Update documentation for any API changes
4. Ensure all tests pass before submitting

## 📄 License

This project is licensed under the Apache License 2.0. See the license headers in source files for details.

## 🔗 References

- [LeetCode Problem #4: Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)
- [Binary Search Algorithm](https://en.wikipedia.org/wiki/Binary_search_algorithm)
- [C++ Core Guidelines](https://isocpp.github.io/CppCoreGuidelines/CppCoreGuidelines)