🧠 What is Sorting?

Sorting means arranging data in a specific order, usually:


✅ Types of Sorting (Basic to Advanced):

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

🧪 Let's start with the easiest:

🔸 Bubble Sort (Ascending)

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


âš¡ STL Sort (Inbuilt)

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] << " ";
}

🧠 Logic of STL sort:

It uses Introsort → hybrid of QuickSort, HeapSort, and InsertionSort.


📚 Practice Problems: