I am for the most part completely lost when it comes to this assignment. I am to write a function that receives an array of pointers to characters. Each pointer in the array points to an array of characters (string).
The function should sort the strings by manipulating their pointers.
The example given is Fall, Spring, Winter, Summer. These seasons should be sorted Fall, Winter, Spring, Summer. Define a main() and print the strings, one of each line, before and after sorting them.
So far... I havent gotten far. I did the program below to simply see if I could get on track. Did I create an array of pointers to characters? It seems so to me. Does anyone have tips or advice for continuing?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include "stdafx.h"
#include <iostream>
usingnamespace std;
int main()
{
char *seasons[4]={"Fall", "Spring", "Winter","Summer"};
for (int i = 0; i < 4; i++ )
{
cout << "\nSeason number " << i+1 << " is " << seasons[i];
}
cout << "\n\n";
system("pause");
return 0;
}
These seasons should be sorted Fall, Winter, Spring, Summer.
Um... How do you want them sorted, because those are not in alphabetical order. Also, do you know what algorithm you are supposed to use to sort this array because there are many of them (including ont in the standard library.)
1 2
//A start might be defining a sort function
void sort(char * array[], int length); //something like this
You mean you need to sort them in not alphabetical, but logical order? In that case, you need some way to tell what the logical order is.
option1: a function int get_position(const char*) which returns 0 if argument is "Fall", 1 if it's "Winter", etc.
option2: an array of integers {0, 2, 1, 3} (so that nth integer represents the position of nth string). Then sort the integer array, but every time you do a swap in it, do one in seasons too.
Are you able to write a sorting algorithm for an array of integers? If not, see bubble sort in wikipedia. They have some pseudocode there which might help.