0% found this document useful (0 votes)
6 views

Algorithm Assignment

Uploaded by

marybavel48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Algorithm Assignment

Uploaded by

marybavel48
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <iostream>

void insertionSort(int arr[], int n) {

for (int i = 1; i < n; ++i) {

int key = arr[i];

int j = i - 1;

while (j >= 0 && arr[j] > key) {

arr[j + 1] = arr[j];

--j;

arr[j + 1] = key;

void printArray(int arr[], int n) {

for (int i = 0; i < n; ++i) {

std::cout << arr[i] << " ";

std::cout << std::endl;

int main() {

int arr[] = {5, 2, 4, 6, 1, 3};

int n = sizeof(arr) / sizeof(arr[0]);

if (n == 0) {

std::cout << "Array is empty. Nothing to sort." << std::endl;


return 1; // Return an error code

std::cout << "Unsorted array: ";

printArray(arr, n);

insertionSort(arr, n);

std::cout << "Sorted array: ";

printArray(arr, n);

return 0;

You might also like