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

Load a Pandas dataframe with a selected dataset. Identify and count the missing values in a dataframe. Clean the data after removing noise as follows: a. Drop duplicate rows. b. Detect the outliers and remove the rows having outliers c. Identify the most correlated positively correlated attributes and negatively correlated attributes

The weights of 8 boys in kilograms: 45, 39, 53, 45, 43, 48, 50, 45. Find the median

Download any dataset and do the following: a. Count number of categorical and numeric features b. Remove one correlated attribute (if any) c. Display five-number summary of each attribute and show it visually