Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
Anyone know how to make this C++ Program (involves 2-D arrays and arranging numbers)?
So the program is is that I have some random array that's a 4 by 5 filled with just numbers, like so:
{16,22,99,4,18,
258,4,101,5,98,
105,6,15,2,45,
33,88,72,16,3}
and I have to create a program that takes those 20 numbers and sorts them in increasing order in a 1-D array called 'sort'.
So far, this is what I have:
void main()
{
system("cls");
const int i = 4;
const int j = 5;
int R, C, S, max;
R = 0;
C = 0;
S = 0;
const int k = 20;
int sort[k];
int DD [i][j] = {16,22,99,4,18,
----------------258,4,101,5,98,
----------------105,6,15,2,45,
----------------33,88,72,16,3};
-------for (C = 0; C < j; C++)
-------{
-------------for (R = 0; R < i; R++)
-------------{
-------------}
-------}
}
So basically, I have nothing right now because I can't logically think this whole process through and I just need a fresh set of eyes to tell me a way to go about doing this. If someone told me how to program it, I could do it, but I can't think of the way to do this program on my own. I'm just stumped on how to do this. (and ignore all the hyphens, just using them to make the program easier to read)
So if anyone could give me some advice on this, I'd greatly appreciate it.
1 Answer
- CalvinLv 47 years ago
Two things: you need a comparison function that determines where the currently processed number fits into the new 1D array and then another function that moves the elements around in the 1D array so the new element can be properly placed.
The process is much the same if you were doing it by hand with index cards that had numbers written on them. The first number is the (current) lowest so it goes in the first spot. You'd compare each new number and rearrange the cards as needed. If you look at your data, for example, processing that would result in 16 being placed in the first location, then compared with 22, which would go after, then 99 is compared to those and stored last but 4 is lower than any of those and so becomes the new "first" element which means you have move the rest "up" a location, etc.
My advice is not to worry about optimizing for speed until you get it working. (And not even then if efficiency is not part of your grade).
You should probably read up on sorting algorithms before you start coding. There are several kinds!