Answer to Question #328235 in C++ for Wedyan

Question #328235

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





1
Expert's answer
2022-04-13T13:24:36-0400
#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] << " ";
	}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS