Create a function (order()), that arranges two numbers in ascending order
Now ask the user to enter three numbers and by using the same function, arrange and display the entered
three numbers in increasing order
#include <iostream>
int find_smallest(int* arr, int i);
void order(int* arr, int n)
{
int pos, temp;
for (int i = 0; i < n; ++i)
{
pos = find_smallest(arr, i);
temp = arr[i];
arr[i] = arr[pos];
arr[pos] = temp;
}
}
int find_smallest(int* arr, int i)
{
int position = i;
int smallest = arr[position], j;
for (j = i + 1; j < 3; j++)
{
if (arr[j] < smallest)
{
smallest = arr[i];
position = j;
}
}
return position;
}
int main()
{
int array[3]{};
std::cout << "Enter three numbers" << std::endl;
for (std::size_t i = 0; i < 3; ++i)
{
std::cin >> array[i];
}
std::cout << "Before sorting" << std::endl;
for (std::size_t i = 0; i < 3; ++i)
{
std::cout << array[i] <<'\t';
}
std::cout << std::endl;
order(array, 3);
std::cout << "After sorting" << std::endl;
for (std::size_t i = 0; i < 3; ++i)
{
std::cout << array[i] << '\t';
}
std::cout << std::endl;
return 0;
}
Comments
Leave a comment