Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I need to write a C++ program that creates a function (sortArr) that sorts an ar

ID: 641729 • Letter: I

Question

I need to write a C++ program that creates a function (sortArr) that sorts an array of integers in either ascending or descending order.

Example Output:

Enter the size of the array: 5

Enter the numbers in the array, separated by a space, and press enter: 4 6 8 2 5

Sort in ascending (0) or descending (1) order? 1

This is the sorted array in descending order: 8 6 5 4 2

If there is any logic confliction, I need it to print out ERROR; An example would be entering an incorrect amount of intergers in relationship with the size of the array.

I also need to write up a program that does the same thing at the top, but uses an insertion sort algorithm for both ascending and descending order.

Explanation / Answer

#include <iostream>

using namespace std;

void getSorted(int *arr, int size, int sign){
   for(int i = 0; i < size - 1; ++i){
       int minInd = i;
       for(int j = i + 1; j < size; ++j){
           if(arr[minInd] > arr[j] && sign == 0){
               minInd = j;
           }
           else if(arr[minInd] < arr[j] && sign == 1){
               minInd = j;
           }
       }
       if(minInd != i){
           int temp = arr[minInd];
           arr[minInd] = arr[i];
           arr[i] = temp;
       }
   }
}

int main(){
   int size, order;
   cout << "Enter the size of the array: ";
   cin >> size;
   int *arr = new int[size];
   cout << "Enter the numbers in the array, separated by a space, and press enter: ";
   for(int i = 0; i < size; ++i){
       cin >> arr[i];
   }
   cout << "Sort in ascending (0) or descending (1) order? ";
   cin >> order;
   if(order != 0 && order != 1){
       cout << "Error: Invalid input" << endl;
   }
   else{
       getSorted(arr, size, order);
       if(order == 0){
           cout << "This is the sorted array in ascending order: ";
       }
       else{
           cout << "This is the sorted array in descending order: ";
       }
       for(int i = 0; i < size; ++i){
           cout << arr[i] << " ";
       }
       cout << endl;
   }
   return 0;
}