Click here to Skip to main content
15,886,258 members
Please Sign up or sign in to vote.
4.20/5 (2 votes)
See more:
Hi. I'm a bit of a newbie in C++, and I'v been working on a program from college and I got a little problem. The thing is, i need to enter 7 elements in a single array in one function, which I did. Now I have to find the smallest and the biggest element in the array and switch their places in another function. How do I do that ? (It is NO homework, it's my personal exercising) The function should look like this:

void switching(float array[], int v) //v is the const int size of the array


Help would be appreciated. :)
Posted

Would look something like this:

C++
// method to switch two elements in an array
void switching(float[] array, int positionX, int positionY)
{
    float temp = array[positionX];
    array[positionX]  = array[positionY];
    array[positionY] = temp;
}


There you have a method that switches two elements in an array.
You'd call that from you other function like this:

...
switching(array, idxOfBiggest, idxOfSmallest);
...


where idxOfBiggest and idxOfSmallest are the indices of the biggest and the smallest array element.

Cheers!
 
Share this answer
 
v2
Comments
Sergey Alexandrovich Kryukov 18-Feb-11 12:04pm    
Sure, 5,
--SA
Option one:
  1. Choose the sort algorithm, implement it.
  2. Using the coded algo find max & min (say v[max], v[min]).

  3. Swap v[max] and v[min] with the usual
    C++
    float tmp = v[max]; v[max] = v[min]; v[min] = tmp


You may replace point (1) with:
Use an existing sorting method, like, for instance STL sort[^].
 
Share this answer
 
Comments
Edin Kalabić 18-Feb-11 6:57am    
Thank you, but I need to write the algorithm for it.
CPallini 18-Feb-11 7:34am    
Do you mean, you have to write yourself the 'sorting algorithm'? If it is just an exercise, then you may code the bubble sort, it is almost trivial to implement.
Edin Kalabić 18-Feb-11 8:20am    
Yes I do.
Sergey Alexandrovich Kryukov 18-Feb-11 12:02pm    
Lope,

You say it's your personal exercise. So, do exercise, otherwise you will never really learn anything!
--SA
Sergey Alexandrovich Kryukov 18-Feb-11 12:03pm    
We know all that, don't we?
My 5,
--SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900