Group
Search and Sort Algorithms in C++
Objective
Create a function called insertionSort that accepts an array of integers and its size. Inside the function, implement the insertion sort algorithm by iterating through the array and inserting each element into its correct position in the sorted portion of the array. In the main function, define an unsorted array and use the insertionSort function to sort it. Finally, print the sorted array.
Create a program that sorts an array using the insertion sort algorithm.
Example C++ Exercise
Show C++ Code
#include <iostream> // Include the input-output stream library
using namespace std;
// Function to perform insertion sort on an array
void insertionSort(int arr[], int size) {
// Loop through elements starting from the second one
for (int i = 1; i < size; i++) {
int key = arr[i]; // Store the current element
int j = i - 1;
// Move elements greater than key to one position ahead
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; // Shift element to the right
j = j - 1; // Move to the previous element
}
arr[j + 1] = key; // Place the key in its correct position
}
}
int main() {
// Declare and initialize an unsorted array
int numbers[] = {9, 5, 1, 4, 3};
int size = sizeof(numbers) / sizeof(numbers[0]); // Calculate array size
// Call the insertionSort function
insertionSort(numbers, size);
// Display the sorted array
cout << "Sorted array: ";
for (int i = 0; i < size; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0; // End of program
}
Output
Sorted array: 1 3 4 5 9