C++ Help: Sorting with Arrays & Merging Strings

  • Context: C/C++ 
  • Thread starter Thread starter scumbum22
  • Start date Start date
  • Tags Tags
    Arrays C++
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
3 replies · 2K views
scumbum22
Messages
6
Reaction score
0
I'm working on programming my own sorting code in C++ using the divide and conquer algorithm. I'm a novice programmer and I've gotten a little stuck.

Let's say you begin your code with an array of distances,

dis[4] = {dis1, dis2, dis3, dis4}

Then I want to separate this array into subarrays. I have the following,

for (i = 0, i = 4, ++i);
if (dis <= dis[0]) { ...?
}
else { ... ? }

I want to somehow make two arrays: One made up of the elements less than or equal to dis[0] and another made up of the elements not following the condition. How should I do this?

Also, is there a way to merge a string of arrays into one array?
 
Physics news on Phys.org
You could create new arrays dynamically as you go, using the new keyword. I don't recommend doing this, though, because it will be harder to develop and debug, and will involve more bookkeeping and memory management code.

You should be able to implement your sorting algorithm using only swaps -- exchanging two elements of the array. This is called an "in-place" sort, because it does not require the allocation of any additional memory.

- Warren
 
If you have access to STL [1] another option is to use instances of stl::vector [2] instead of arrays. That will allow you to concentrate on the algorithmic aspect of your code and let (most of) the memory allocation be taken care of automatically. Of course, STL comes with its own set of idioms that may take a while to learn, but overall it is an improvement compared to coding dynamic arrays "manually".

[1] http://www.sgi.com/tech/stl/
[2] http://www.cplusplus.com/reference/stl/vector/
 
Note: I put [ code ] and [ /code ] tags (without the extra spaces) around your code.
scumbum22 said:
Let's say you begin your code with an array of distances,

dis[4] = {dis1, dis2, dis3, dis4}

Then I want to separate this array into subarrays. I have the following,
Code:
for (i = 0, i = 4, ++i);
    if (dis[i] <= dis[0]) { ...?
    }
        else { ... ? }
I see at least four problems with your code sample here.
1) The three expressions in parentheses for the for loop need to be separated by semicolons, not commas.
2) The middle expression should be i < 4.
3) There should not be a semicolon on the line with the for statement.
4) To avert hard to find bugs, you should put braces ({}) to mark the body of your for loop. IOW, it should look something like this:
Code:
for (i = 0; i < 4, ++i)
{
    if (dis[i] <= dis[0]) { ...? }
    else { ... ? }
}