Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Insertion Sort in cpp #365

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
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
43 changes: 43 additions & 0 deletions Insertion Sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
//A bookstore manager needs to organize the prices of books in ascending order so that customers can easily find affordable options. The prices of the books are: [299, 150, 89, 450, 120, 350, 199, 99, 275, 400]
//Using the Insertion Sort algorithm, sort the book prices in ascending order.

#include <iostream>
using namespace std;

// Function to perform insertion sort
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;

// Move elements of arr[0..i-1] that are greater than key to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

// Function to print the array
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}

int main() {
int prices[] = {299, 150, 89, 450, 120, 350, 199, 99, 275, 400};
int n = sizeof(prices) / sizeof(prices[0]);

cout << "Original prices: ";
printArray(prices, n);

insertionSort(prices, n);

cout << "Sorted prices: ";
printArray(prices, n);

return 0;
}