Data-Structures-with-Go/array-rotation/README.md

54 lines
1.4 KiB
Markdown
Raw Normal View History

2017-10-26 10:44:56 +00:00
<h1 align="center">Array Rotation Source</h1>
2017-10-25 12:15:05 +00:00
[What It Is](#what-it-is)
## What It Is
2017-10-26 10:44:56 +00:00
> * Input: Write a function `rotate(ar[], d, n)` that rotates `arr[]` of size `n` by `d` elements
> * Output: `1 2 3 4 5 6 7`
2017-10-26 10:01:42 +00:00
2017-10-26 10:44:56 +00:00
> * Input: Rotation of the above array by `2` will make array
> * Output: `3 4 5 6 7 1 2`
2017-10-25 12:15:05 +00:00
2017-10-26 11:04:30 +00:00
METHOD 1 (Use temp array)
--------------------------
2017-10-25 12:15:05 +00:00
Input arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2, n =7
2017-10-25 12:16:21 +00:00
* 1) Store `d` elements in a temp array
2017-10-25 12:15:05 +00:00
temp[] = [1, 2]
2017-10-25 12:16:21 +00:00
* 2) Shift rest of the `arr[]`
2017-10-25 12:15:05 +00:00
arr[] = [3, 4, 5, 6, 7, 6, 7]
2017-10-25 12:16:21 +00:00
* 3) Store back the `d` elements
2017-10-25 12:15:05 +00:00
arr[] = [3, 4, 5, 6, 7, 1, 2]
2017-10-26 11:04:30 +00:00
**Algorithm Complexity**
2017-10-25 12:15:05 +00:00
| Complexity | Notation |
| ----------------- |:---------:|
| `Time Complexity` | `O(n)` |
| `Auxiliary Space` | `O(d)` |
2017-10-26 11:04:30 +00:00
METHOD 2 (Rotate one by one)
--------------------------
2017-10-25 12:15:05 +00:00
```go
leftRotate(arr[], d, n)
start
For i = 0 to i < d
Left rotate all elements of arr[] by one
end
```
To rotate by one, store arr[0] in a temporary variable temp, move arr[1] to arr[0], arr[2] to arr[1] …and finally temp to arr[n-1]
Let us take the same example arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2
Rotate arr[] by one 2 times
We get `[2, 3, 4, 5, 6, 7, 1]` after first rotation and `[3, 4, 5, 6, 7, 1, 2]` after second rotation.
2017-10-26 11:04:30 +00:00
**Algorithm Complexity**
2017-10-25 12:15:05 +00:00
| Complexity | Notation |
| ----------------- |:---------:|
| `Time Complexity` | `O(n*d)` |
2017-10-26 10:38:59 +00:00
| `Auxiliary Space` | `O(1)` |