Вопрос задан 29.07.2023 в 09:29. Предмет Информатика. Спрашивает Ткаленко Діана.

Есть код: #include<iostream> #include<ctime> using namespace std; int main() {

setlocale(LC_ALL, "rus"); srand(time(NULL)); int arr[15]; cout << "Неотсортированный массив из 15 случайных чисел: { "; for (int i = 0; i < 15; i++) { arr[i] = 0 + rand() % (20) - 10; cout << arr[i] << " "; } cout <<"}"<< endl; cout << "Отсортированный массив: [ "; for (int i = 0; i < 15; i++) { for (int j = i+1; j < 15; j++) { if (arr[i] > arr[j]) { swap(arr[i], arr[j]); } } } for (int i = 0; i < 15; i++) cout << arr[i]<<" "; cout << "]" << endl; return 0; } Задание: числа в массиве - рандомные, нужно их отсортировать так: сначала отрицательные на уменьшение, потом положительные на уменьшение. У меня только по возрастанию сортировать получаеться(
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Кудрявцев Максим.

//Microsoft (R) C/C++ Optimizing Compiler Version 19.00.23506 for x64
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> mas = { 1, 5, -4, 9, -6, -2, 7, 8, -5, 0 };
auto it = std::partition(mas.begin(), mas.end(), [](const int& i) { return i < 0; });
std::sort(mas.begin(), it, [](const int& x, const int& y) { return x > y; });
std::sort(it, mas.end(), [](const int& x, const int& y) { return x > y; });
std::copy(mas.begin(), mas.end(), std::ostream_iterator<int>(std::cout, " "));
}

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

To sort the numbers in the array first by decreasing negative numbers and then by decreasing positive numbers, you need to modify the sorting logic in your code. Instead of using a simple selection sort as you have currently, you can use a custom sorting function that handles negative and positive numbers separately.

Here's the modified code to achieve the required sorting:

cpp
#include <iostream> #include <ctime> using namespace std; bool compare(int a, int b) { if (a < 0 && b < 0) { return a > b; // For negative numbers, sort in decreasing order } else if (a >= 0 && b >= 0) { return a > b; // For positive numbers, sort in decreasing order } else { return a < b; // For mixed signs, negative numbers come before positive numbers } } int main() { setlocale(LC_ALL, "rus"); srand(time(NULL)); int arr[15]; cout << "Неотсортированный массив из 15 случайных чисел: { "; for (int i = 0; i < 15; i++) { arr[i] = 0 + rand() % 20 - 10; cout << arr[i] << " "; } cout << "}" << endl; // Custom sorting using the compare function for (int i = 0; i < 15; i++) { for (int j = i + 1; j < 15; j++) { if (compare(arr[i], arr[j])) { swap(arr[i], arr[j]); } } } cout << "Отсортированный массив: [ "; for (int i = 0; i < 15; i++) cout << arr[i] << " "; cout << "]" << endl; return 0; }

The compare function is used in the sorting algorithm to determine the order of two elements. For negative numbers, it sorts them in decreasing order (larger negatives come first), and for positive numbers, it also sorts them in decreasing order (larger positives come first). Mixed sign numbers will have negative numbers come before positive numbers.

With this custom sorting function, the array will be sorted as desired with negative numbers decreasing first and then positive numbers decreasing.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос