C++ Algorithms
Sorting Algorithms
Common sorting algorithms implementation in C++.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Bubble Sort
void bubbleSort(vector<int>& arr) {
int n = arr.size();
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]);
}
// Quick Sort
int partition(vector<int>& arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for(int j = low; j < high; j++) {
if(arr[j] <= pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i + 1], arr[high]);
return i + 1;
}
void quickSort(vector<int>& arr, int low, int high) {
if(low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
CPP UTF-8
Lines: 31
Search Algorithms
Implementation of various search algorithms.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Linear Search
int linearSearch(vector<int>& arr, int target) {
for(int i = 0; i < arr.size(); i++)
if(arr[i] == target)
return i;
return -1;
}
// Binary Search (Iterative)
int binarySearch(vector<int>& arr, int target) {
int left = 0, right = arr.size() - 1;
while(left <= right) {
int mid = left + (right - left) / 2;
if(arr[mid] == target)
return mid;
if(arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1;
}
CPP UTF-8
Lines: 24
Practice: Implement Merge Sort
Try implementing the merge sort algorithm.
Output
Ready