Hello,
So I have to write a function called sortMe that sorts the elements of an array in numerical order from highest to lowest values (descending order) or vice versa (ascending order).
I was able to this but not how I'm supposed to.
The assignment asks to: NOT re-arrange elements in the array; instead, it uses a second array, an array of indexes for the elements in the original array and then sortMe sorts the second array based on the values in the original
array. A sorted version of the original array can then be produced with these sorted indexes.
Header of the function sortMe must be as shown below:
void sortMe(int array[],int sortedIndexes [], int size, char mode)
When mode is 'a', the function sorts the array in the ascending order, and when mode is 'd', the function sorts it in the descending order.
Declare and initialize the array array.
Declare the array sortedIndexes but do not initialize it. You are going to play with the array sortedIndexes in the
function sortMe.
EXAMPLE:
int array[5]={3, 5,-1,10,0};
int sortedIndexes[5];
sortMe(array,sortedIndexes, 5, 'a');
After the function call, the elements of the array sortedIndexes should
be: 2,4,0,1,3
Please notice that the function does not e-arrange the elements in the array.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
using namespace std;
void sortMe(int[], int, char);
void main()
{
int arr[6] = { 14, -5, 5, 0, 22, -99 };
char input;
cout << "Please select in what order you want the numbers sorted. \nFor ascending order press a. For descending order press d: \n";
cin >> input;
if (input == 'a'){
sortMe(arr, 6, 'a');
for (int i = 0; i < 6; i++)
cout << arr[i] << "\t"; //I want to print the sortedIndexes array not array
}
else if (input == 'd'){
sortMe(arr, 6, 'd');
for (int j = 0; j < 6; j++)
cout << arr[j] << "\t";
}
else
cout << "Please make a correct selection" << endl;
system("pause");
}
void sortMe(int array[], int size, char mode)
{
int temp;
if (mode == 'd') //descending order
{
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[j] > array[i])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
else if (mode == 'a') //ascending order
for (int i = 0; i < size; i++)
{
for (int j = i + 1; j < size; j++)
{
if (array[j] < array[i])
{
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
}
}
|
So I got it to ascend and descend by choosing a mode but I did this by rearranging, which is what it asks me not to do