Reputation: 3784
So the exam question is this:
Write a method using the method header below.
public void Reverse( double [] values, int start, int finish){
This method will reverse the elements in an array between a lower index position and an upper index position.
So given the following array declaration
double [] data = {8.5, 12.0, 23.2, 18.0, 15.5, 5.0, 10.5};
following a call to the method
Reverse(data, 2, 5);
the contents of data would be{8.5, 12.0, 5.0, 15.5, 18.0, 23.2, 10.5}
Assume that you have already written a method called swap that swaps two elements in an array; the elements identified by the two index values passed as parameters:
Swap(array, oneIndex, otherIndex)
I answered it like this:
public void Reverse( double [] values, int start, int finish){
do {
Swap(values, int start, int finish);
}
start++;
finish--;
}
while (start < finish)
I think my answer is not correct but I cannot think of anything else. Swap()
method already does everything. Anyone can correct me? Thanks
Upvotes: 0
Views: 2153
Reputation: 33
Heres two more possible answers:
static void Reverse(int[] values, int start, int finish)
{
int end = finish;
for (int i = start; i < end ; i++)
{
Swap(values, i, end);
end--;
}
}
static void Reverse2(int[] values, int start, int finish)
{
int upper = finish;
int lower = start;
while (upper > lower)
{
Swap(values, lower, upper);
lower++;
upper--;
}
}
Upvotes: 0
Reputation: 862
If you will work a little bit on paranthesis within your function and remove ints from function call it will work.
public static void Swap(double[] values, int firstIndex, int secondIndex)
{
double temp = values[start];
values[start] = values[finish];
values[finish] = temp;
}
public static void Reverse( double [] values, int start, int finish)
{
do
{
Swap(values, start, finish);
start++;
finish--;
}
while (start < finish);
}
static void Main(string[] args)
{
double[] data = { 8.5, 12.0, 23.2, 18.0, 15.5, 5.0, 10.5 };
Reverse(data, 2, 5);
foreach (double number in data)
Console.Write(number.ToString() + ", ");
Console.ReadKey();
}
Gives:
8.5, 12, 5, 15.5, 18, 23.2, 10.5,
Upvotes: 0
Reputation: 2123
Swap accepts oneIndex and otherIndex, not start and finish.
What you missed is the loop between start and finish, in which you have to call the swap method with each iterated number:
int iterationsNum = (finish - start) / 2 ;
for(int i=0;i<=iterationsNum;i++)
{
if(start+i != finish-i)
{
swap(values, start+ i, finish-i);
}
}
probably theres a way to remove the uneeded iteration where I checkked if the indexes are the same, but this is the basic concept.
Upvotes: 2