Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions Algorithms/Sort/InsertionSort/InsertionSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
#include <iostream>
#include <vector>

/**
* @brief Perform Insertion Sort on a vector.
*
* This function sorts the elements of the vector in ascending order using the
* Insertion Sort algorithm.
*
* @param array Reference to the vector to be sorted.
*/
void insertionSort(std::vector<int>& array) {
int arrayLength = array.size();

for(int i = 1; i < arrayLength; i++){
int key = array[i];
int j = i - 1;

// Moving elements greater than key to one position ahed
while(j >= 0 && array[j] > key) {
array[j + 1] = array[j];
j = j - 1;
}

array[j + 1] = key;
}
}

int main() {
std::vector<int> exampleArray = {4, 1, 5, 8, 8, 10, 21, 0, -3, 2, 1, 3};

std::cout << "Original array: ";
for (int elem : exampleArray) {
std::cout << elem << " ";
}
std::cout << std::endl;

insertionSort(exampleArray);

std::cout << "Sorted array: ";
for (int elem : exampleArray) {
std::cout << elem << " ";
}
std::cout << std::endl;

return 0;
}