Welcome to Searching Sorting CodeSnap
The 'Searching & Sorting' category covers fundamental algorithms for organizing and retrieving data efficiently. Searching algorithms, like Binary Search, focus on finding specific elements within a dataset, typically leveraging sorted structures for logarithmic time performance. Sorting algorithms, such as Quick Sort or Merge Sort, arrange elements in a specific order (e.g., ascending or descending). Mastery of these techniques is crucial for optimizing data handling, enabling faster lookups, and serving as a prerequisite for more complex algorithms. Problems often involve implementing these algorithms or applying variations like finding insertion points or specific ranked elements (e.g., Kth largest).
Table of Contents
Binary Search
Implement the classic binary search algorithm. Given a sorted array of integers `nums` and an integer `target`, write a function to search `target` in `nums`. If `target` exists, return its index. Otherwise, return -1. This algorithm works by repeatedly dividing the search interval in half.
Search Insert Position
Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order while maintaining the sorted property. Uses a modified binary search.
Merge Sorted Arrays
Given two sorted integer arrays `nums1` and `nums2`, merge `nums2` into `nums1` as one sorted array. The number of elements initialized in `nums1` and `nums2` are `m` and `n` respectively. Assume that `nums1` has enough space (size `m + n`) to hold additional elements from `nums2`. The merge should be done in-place.
Quick Sort Implementation
Implement the Quick Sort algorithm to sort an array of integers. Quick Sort is an efficient, in-place, comparison-based sorting algorithm that uses a divide-and-conquer strategy by partitioning the array around a pivot element.
Kth Largest Element in an Array
Given an integer array `nums` and an integer `k`, return the k-th largest element in the array. Note that it is the k-th largest element in the sorted order, not the k-th distinct element. Common approaches include sorting, using a min-heap, or the QuickSelect algorithm.