Sorting means arranging data in a specific order, usually:
| Type | Time Complexity | Use Case |
|---|---|---|
| Bubble Sort | O(n²) | Easy to understand |
| Selection Sort | O(n²) | Minimal swaps |
| Insertion Sort | O(n²) | Good for nearly sorted arrays |
| Merge Sort | O(n log n) | Stable & efficient (Divide & Conquer) |
| Quick Sort | O(n log n) avg | Fast & widely used |
STL sort() |
O(n log n) | Super fast and optimized |
cpp
Copy code
#include<iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for(int i = 0; i < n-1; i++) {
// Last i elements are already sorted
for(int j = 0; j < n-1-i; j++) {
if(arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
}
}
}
}
int main() {
int arr[] = {5, 2, 9, 1, 6};
int n = 5;
bubbleSort(arr, n);
cout << "Sorted array: ";
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
}
🧾 Output:
php
Copy code
Sorted array: 1 2 5 6 9
cpp
Copy code
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int arr[] = {5, 1, 8, 3, 2};
int n = 5;
sort(arr, arr + n); // Ascending
// sort(arr, arr + n, greater<int>()); // Descending
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
}
It uses Introsort → hybrid of QuickSort, HeapSort, and InsertionSort.