Write a c++ program which sorts elements of array in both as increasing and decreasing order ?
HINT; - Size of array =10
- Data type = int
- Name of array = data
- Accept all input from user
#include <iostream>
#include <array>
const int SIZE = 10;
void increasing_sort(std::array<int, SIZE>& data)
{
int temp = 0;
for (int i = 1; i < SIZE; i++)
{
bool is_sorted = true;
for (int j = 0; j < SIZE - i; j++)
{
if (data[j] > data[j + 1])
{
temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
is_sorted = false;
}
}
if (is_sorted)
{
break;
}
}
}
void decreasing_sort(std::array<int, SIZE>& data)
{
int temp = 0;
for (int i = 1; i < SIZE; i++)
{
bool is_sorted = true;
for (int j = 0; j < SIZE - i; j++)
{
if (data[j] < data[j + 1])
{
temp = data[j];
data[j] = data[j + 1];
data[j + 1] = temp;
is_sorted = false;
}
}
if (is_sorted)
{
break;
}
}
}
int main()
{
std::array<int, SIZE> data;
std::cout << "Enter 10 array elements: ";
for (int i = 0; i < SIZE; ++i)
{
std::cin >> data[i];
}
increasing_sort(data);
std::cout << "Increasing order sort result : ";
for (int i = 0; i < SIZE; ++i)
{
std::cout << data[i] << " ";
}
std::cout << std::endl;
decreasing_sort(data);
std::cout << "Decreasing order sort result : ";
for (int i = 0; i < SIZE; ++i)
{
std::cout << data[i] << " ";
}
}
Comments
Leave a comment