Skip to content

Commit 4bf9922

Browse files
authored
Add insertion sort
1 parent 09756d4 commit 4bf9922

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

src/insertion_sort.cpp

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#include <iostream>
2+
#include <string>
3+
4+
#define SIZE 10
5+
6+
// Function prototypes
7+
void printArray(int array[]);
8+
void insertionSort(int array[SIZE]);
9+
10+
/**
11+
* @brief Main function that demonstrates the sorting algorithm.
12+
*
13+
* Initializes an array of integers, prints it, sorts it using the insertion sort
14+
* algorithm, and prints the sorted array.
15+
*
16+
* @return int Status code (0 for success)
17+
*/
18+
19+
int main()
20+
{
21+
// Initialize an array of integers in descending order
22+
int array[SIZE]{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
23+
24+
// Print the original array
25+
printArray(array);
26+
std::cout << std::endl;
27+
28+
// Sort the array using insertion sort
29+
insertionSort(array);
30+
31+
// Print the sorted array
32+
printArray(array);
33+
34+
std::cout << std::endl;
35+
system("PAUSE");
36+
return 0;
37+
}
38+
39+
/**
40+
* @brief Prints the elements of an integer array.
41+
*
42+
* This function takes an array of integers and prints each element separated
43+
* by a pipe ('|') for easy readability.
44+
*
45+
* @param array The integer array to be printed
46+
*/
47+
48+
void printArray(int array[])
49+
{
50+
// Loop through each element of the array and print it with separators
51+
for (int i = 0; i < SIZE; ++i)
52+
{
53+
std::cout << " |" << array[i] << "| ";
54+
}
55+
}
56+
57+
/**
58+
* @brief Sorts an array using the Insertion Sort algorithm.
59+
*
60+
* The Insertion Sort algorithm works by repeatedly taking the next element in the array
61+
* and comparing it to the elements before it, shifting larger elements one position to the
62+
* right, and inserting the current element into its correct position.
63+
*
64+
* @param array The integer array to be sorted
65+
*/
66+
67+
void insertionSort(int array[SIZE])
68+
{
69+
int currentElement, position;
70+
71+
// Loop through each element starting from the second (index 1)
72+
for (int i = 1; i < SIZE; i++)
73+
{
74+
// The current element being analyzed
75+
currentElement = array[i];
76+
77+
// The position of the element just before the one being analyzed
78+
position = i - 1;
79+
80+
// Shift elements that are greater than the current element one position to the right
81+
while (position >= 0 && currentElement < array[position])
82+
{
83+
array[position + 1] = array[position]; // Move the element one position ahead
84+
position--; // Move to the previous element
85+
}
86+
87+
// Place the current element in its correct position
88+
array[position + 1] = currentElement;
89+
}
90+
}

0 commit comments

Comments
 (0)