How to implement a cyclic shift of the elements of the array to the right in the loop?
4 answers
The solution to the forehead may look like this.
if ( a.Length > 1 ) { var tmp = a[a.Length - 1]; for ( var i = a.Length - 1; i != 0; --i ) a[i] = a[i-1]; a[0] = tmp; }
|
Here, the (C) code seems to be lying around (seemingly efficient). I think it's easy to adapt to sharpe.
// rotate(): http://codelab.ru/task/cycle_shift/ void swap (int a[], int f, int t, int l) { int tt; for (l+=f; f < l; f++,t++) { tt = a[f]; a[f] = a[t]; a[t] = tt; } } void rotate (int a[], int n, int dist) { if ((dist %= n) == 0) return; if (dist < 0) dist += n; int i, j, p; i = p = dist; j = n - p; while (i != j) { if (i > j) { swap (a, pi,p,j); i -= j; } else { swap (a, pi,p+ji,i); j -= i; } } swap (a, pi,p,i); }
|
var temp = source[source.Length-1]; Array.Copy(source, 0, source, 1, source.Length - 1); source[0] = temp;
Where source is an array. According to the tests, this method works many times faster than the proposed cycle. This can be explained by the fact that in the loop the elements are copied one by one, and this method immediately copies everything that was told to it.
- You have a normal shift, but you need a cyclic shift - Pavel Mayorov
- @PavelMayorov fixed. Again, this method will work much faster than the cycle in which each element is shifted separately. - Daniel Shatz
- Here only your code now does not work. At the entrance - [1,2,3,4,5], at the output - [5,3,4,5,5]! - Pavel Mayorov
- oneFixed, shtop worked as requested. - Pavel Mayorov
|
if (diff > 0) { //Сдвигаем влево var temp = new short[diff]; Array.Copy(timeArr, temp, diff); Array.Copy(timeArr, diff, timeArr, 0, timeArr.Length - diff); Array.Copy(temp, 0, timeArr, timeArr.Length - diff, temp.Length); } else { //Сдвигаем вправо diff = -diff; var temp = new short[diff]; Array.Copy(timeArr, timeArr.Length - diff, temp, 0, diff); Array.Copy(timeArr, 0, timeArr, diff, timeArr.Length - diff); Array.Copy(temp, 0, timeArr, 0, temp.Length); }
timeArr - an array that needs to be moved according to the circular buffer principle. diff - how much to shift, right or left.
|