An array of size N is given. Reverse the order of its elements.

How to solve? How to start?

  • To issue a task to an array using lamda expressions. Get the elements of the array using Random - cat

3 answers 3

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]; } 
  • thank you very much) you helped me a lot - cat
  • 3
    best thanks - mark the correct answer - Specter
  • yield return this is not understood (and is that all or something? - cat
  • 2
    the keyword [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. - Specter
  • one
    when the original array has changed .... - timka_s

The 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 ...

  • I think they are learning) And if the array is not even? ) This is a pitfall for this algorithm. - Gena Ant
  • no it's not a stone. the cycle will reach the middle element and stop. - skegg
  • one
    In addition - the middle element-zhezh should not be moved ... - timka_s
  • yep exactly. - skegg
  • 2
    By definition, the middle element is i == j. The condition for continuing the cycle is i <j. “From what it clearly follows,” there will be no excess exchange. - avp

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++; } 
  • 2
    you have a lot of code mistakes - Specter