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
Post a Comment