Junior — Middle
Which sorting algorithm is considered the most efficient for general use?
sobes.tech AI
Answer from AI
The most effective and widely used sorting algorithm for general purposes is QuickSort. It has an average time complexity of O(n log n) and generally performs faster than other algorithms in practice due to good data locality and simplicity of implementation.
However, it is important to consider that in the worst case, QuickSort can work in O(n²), so some implementations use hybrid approaches, such as switching to insertion sort for small arrays.
Example of using QuickSort in C++:
#include <iostream>
#include <vector>
void quickSort(std::vector<int>& arr, int left, int right) {
int i = left, j = right;
int pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot) i++;
while (arr[j] > pivot) j--;
if (i <= j) {
std::swap(arr[i], arr[j]);
i++; j--;
}
}
if (left < j) quickSort(arr, left, j);
if (i < right) quickSort(arr, i, right);
}
int main() {
std::vector<int> data = {3, 6, 8, 10, 1, 2, 1};
quickSort(data, 0, data.size() - 1);
for (int num : data) {
std::cout << num << " ";
}
return 0;
}