Searching and Sorting Algorithms
What is Searching?
Searching is the process of finding a specific element (called the key) in a data structure like an array or list.
Types of Searching Techniques:
1. Linear Search:
Check each element one by one.
Time Complexity: O(n)
C++ Example:
int linearSearch(int arr[], int n, int key) {
for(int i = 0; i < n; i++) {
if(arr[i] == key)
return i;
return -1;
2. Binary Search:
Divide the sorted array and search in halves.
Time Complexity: O(log n)
C++ Example:
int binarySearch(int arr[], int n, int key) {
int low = 0, high = n - 1;
while(low <= high) {
int mid = (low + high) / 2;
if(arr[mid] == key) return mid;
else if(arr[mid] < key) low = mid + 1;
else high = mid - 1;
return -1;
}
3. Jump Search:
Jump fixed steps and then do linear search.
Time Complexity: O(sqrt(n))
4. Interpolation Search:
Position is guessed using interpolation formula.
Time Complexity: Best: O(log log n), Worst: O(n)
5. Exponential Search:
Double the index and then apply binary search.
Time Complexity: O(log i)
What is Sorting?
Sorting means arranging data in order (ascending or descending).
Popular Sorting Algorithms:
1. Bubble Sort:
Repeatedly swap adjacent elements.
Time Complexity: O(n^2)
C++ Example:
void bubbleSort(int arr[], int n) {
for(int i = 0; i < n-1; i++)
for(int j = 0; j < n-i-1; j++)
if(arr[j] > arr[j+1])
swap(arr[j], arr[j+1]);
2. Selection Sort:
Find the minimum element and place it at the beginning.
Time Complexity: O(n^2)
3. Insertion Sort:
Insert elements into their correct place one by one.
Time Complexity: O(n^2), Best case: O(n)
4. Merge Sort:
Divide and merge subarrays.
Time Complexity: O(n log n)
5. Quick Sort:
Partition around pivot and sort subarrays.
Time Complexity: Best: O(n log n), Worst: O(n^2)
6. Heap Sort:
Convert to heap and extract max/min.
Time Complexity: O(n log n)
7. Radix Sort:
Sort based on digits.
Time Complexity: O(nk), where k is number of digits.
Conclusion:
Use linear search for unsorted data. Use binary/exponential search for sorted data.
Use quick/merge/heap sort for large datasets.