Скласти програму, за якою: заповнити масив А(N) випадковим чином із діапазону [100, 999]; вивести елементи масиву на екран в рядок; упорядкувати діапазон елементів масиву за таких умов: від 1 до 33, кратні 3, метод вставка. вивести елементи масиву на екран в рядок.
С++
Ответы
Відповідь:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
const int N = 33;
void fillArray(int a[], int n)
{
srand(time(0));
for (int i = 0; i < n; i++)
a[i] = 100 + rand() % 900;
}
void printArray(int a[], int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
void insertSort(int a[], int n)
{
for (int i = 1; i < n; i++)
{
int current = a[i];
int j = i - 1;
while (j >= 0 && a[j] % 3 == 0 && a[j] > current)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = current;
}
}
int main()
{
int a[N];
fillArray(a, N);
cout << "Original array: ";
printArray(a, N);
insertSort(a, N);
cout << "Sorted array: ";
printArray(a, N);
return 0;
}
Пояснення: