Implement Insertion sort.


Implement Insertion sort.




 #include <iostream>

#include <vector>


using namespace std;


void insertionSort(vector<int>& arr) {

    int n = arr.size();


    for (int i = 1; i < n; i++) {

        int key = arr[i];

        int j = i - 1;


        // Move elements greater than the key to one position ahead

        while (j >= 0 && arr[j] > key) {

            arr[j + 1] = arr[j];

            j--;

        }


        // Place the key in its correct position

        arr[j + 1] = key;

    }

}


// Function to display the elements of an array

void displayArray(const vector<int>& arr) {

    for (int i = 0; i < arr.size(); i++) {

        cout << arr[i] << " ";

    }

    cout << endl;

}


int main() {

    vector<int> arr = {7, 2, 4, 1, 5, 3};

    

    cout << "Original array: ";

    displayArray(arr);


    insertionSort(arr);


    cout << "Sorted array: ";

    displayArray(arr);


    return 0;

}


Comments

Popular posts from this blog

Using Titanic dataset, do the following: a. Find total number of passengers with age less than 30 b. Find total fare paid by passengers of first class c. Compare number of survivors of each passenger class

Differentiate between Unimodal, Bimodal and Multimodal with graphic representation.

Import iris data using sklearn library . Compute mean, mode, median, standard deviation, confidence interval and standard error for each feature ii. Compute correlation coefficients between each pair of features and plot heatmap iii. Find covariance between length of sepal and petal iv. Build contingency table for class feature