Write a function that rearranges a given descending order array into ascending order without using any sorting algorithm

Introduction:

Suppose that the elements of a list are in descending order and they need to be put in ascending order. Write a C++ function that takes an array of items in descending order and the number of elements in the array as input. The function rearranges the elements of the array in ascending order. Your function must not incorporate any sorting algorithms, that is, no item comparisons should take place.

Source: MindTap Computing for Malik's C++ Programming From Problem Analysis to Program Design, 8th Edition, [Instant Access] (8th)-Malik, chapter 16, programming exercises 18.
Solved!

This program aims to write a function that rearranges a given descending order array into ascending order without using any sorting algorithm.

Program Plan:

·       Define program header.

·       Define rearrange() which take arguments int arr[], int n.

o   For loop i from 0 to n/2.

§  Swap ith and ith last element using swap(arr[i], arr[n - 1 - i]);.

·       Define main() function.

o   Declare int n variable.

o   Use cout << to ask the user to input.

o   Use cin >> n to take user input.

o   Declare array arr[] of size n, this input should be in sorted order.

o   Use for loop to take user input.

o   Make function call rearrange(arr, n);

o   Use for loop to print each element using cout.

Program:


// Object of this program is to write the function
// which rearrange given descending order array into ascending order
// without using any sorting algorithm

#include <iostream>

using namespace std;

// rearrange() function which take array and array size.
void rearrange(int arr[], int n)
{
    // for loop for half value of n.
    // for loop i from 0 to n/2-1.
    for (int i = 0; i < n / 2; i++)
    {
        // swap ith element with ith last element.
        swap(arr[i], arr[n - 1 - i]);
    }
}

// driver function
int main()
{
    // ask array size.
    int n;
    cout << "Enter number of integers:";
    cin >> n;
    // fill array of size n with user input.
    int arr[n];
    cout << "Enter " << n << " integers in descending order:";
    for (int i = 0; i < n; i++)
    {
        // fill each element.
        cin >> arr[i];
    }

    // call to rearrange.
    rearrange(arr, n);
    // print array after rearrangement.
    cout << "Array after rearrangement:";
    for (int i = 0; i < n; i++)
    {
        cout << arr[i] << ", ";
    }
    cout << endl;

    // end.
    return 0;
}

Output:




Image:



Post a Comment

0 Comments