An array of size N is given. Reverse the order of its elements.
How to solve? How to start?
The easiest option is to use the built-in reverse function:
void Main() { int[] a = {1,2,3,4,5,6,7,8,9}; a.Reverse();//вернёт массив в обратном порядке }
the second is to write the reverse yourself:
public static IEnumerable<int> Reverse(int[] array) { for(int i = array.Length-1; i >= 0; i--) yield return array[i]; }
[yield](http://msdn.microsoft.com/ru-ru/library/dscyy5s0.aspx)
means that the function will not stop its execution after the return
, i.e. some value will return, but the function will continue its work from the place of returning the value. - SpecterThe simplest and most effective version of this algorithm (regardless of C #, C, Pascal, Java, Basic ...) in the loop changes the values of the first with the last, the second with the last but one, etc.
Those. for array a [] of length n:
for (i = 0, j = n-1; i < j; i++, j--) { t = a[i]; a[i] = a[j]; a[j] = t; }
I do not understand why this is not taught in lectures, seminars ...
The simplest option is to declare a new variable in which the resulting array will be stored, and in a loop that will go from the maximum to the minimum elements in the original array to fill it. That is, something like this:
int [] a = {1,2,3,4,5,6,7,8,9}; // исходный массив int [] b; // желаемый массив int j = 0; for( int i = a.sizeof(); i = 0; i-- ) { b[j] = a[i]; j++; }
Source: https://ru.stackoverflow.com/questions/67892/
All Articles