168k views
2 votes
Write a program that does the following:

1. Asks the user to enter 10 integers.
2. Stores the input values in an array.
3. Sorts the contents of the array in ascending order, using the insertion sort algorithm.
4. Display the contents of the array after they have been sorted.

1 Answer

6 votes

PYTHON

# Ask the user to enter 10 integers

print("Enter 10 integers:")

array = []

for i in range(10):

array.append(int(input()))

# Sort the array using insertion sort

for i in range(1, len(array)):

key = array[i]

j = i - 1

while j >= 0 and key < array[j]:

array[j + 1] = array[j]

j -= 1

array[j + 1] = key

# Display the sorted array

print("Sorted array:")

print(array)

C++

#include <iostream>

using namespace std;

int main() {

int array[10];

int i, j, key;

// Ask the user to enter 10 integers

cout << "Enter 10 integers: ";

for (i = 0; i < 10; i++) {

cin >> array[i];

}

// Sort the array using insertion sort

for (i = 1; i < 10; i++) {

key = array[i];

j = i - 1;

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

array[j + 1] = array[j];

j--;

}

array[j + 1] = key;

}

// Display the sorted array

cout << "Sorted array: ";

for (i = 0; i < 10; i++) {

cout << array[i] << " ";

}

cout << endl;

return 0;

}

User MustangDC
by
7.9k points