While exploring algorithms in Swift, couldn't find algorithm for array rotation in swift without using funcs shiftLeft
/ shiftRight
.
C has this graceful algo with time complexity of O(N):
/* Function to left rotate arr[] of size n by d */
void leftRotate(int arr[], int d, int n)
{
rvereseArray(arr, 0, d-1);
rvereseArray(arr, d, n-1);
rvereseArray(arr, 0, n-1);
}
/*Function to reverse arr[] from index start to end*/
void rvereseArray(int arr[], int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
I'm struggling with converting this into swift:
func rotate(array:[Int], positions:Int, arSize:Int) {
var a = array
var p = positions
var s = arSize
reverseArray(array: a, start: 0, end: p-1)
reverseArray(array: a, start: p, end: s-1)
reverseArray(array: a, start: 0, end: s-1)
}
func reverseArray(array: [Int], start:Int, end:Int) {
var a = array
var s = start
var e = end
var temp = 0
while s < e {
temp = a[s]
a[s] = a[e]
a[e] = temp
s += 1
e -= 1
}
}
As I understand, for swift, we need to specify return types. How they should be configured without increasing space(memory) complexity? (aka, without creating new temporary arrays)
This question is different from others, because its about how returns
work in swift compare to C.
// a is the array to be left rotated // d is the number of unit for left rotation
// calling Function
// OutPut [5, 1, 2, 3, 4]
We can use Slice
Edit update:
Swift 5 or later
To be complete, the rotation function should support negative (right) rotations and rotating more than the array's size
We can do it using Array's dropFirst() and dropLast() functions.
This solution rotates the element of time complexity O(n)
you shouldn't use
.append(x)
as in the worst case it can be O(n) and you shouldn't use.remove(at: x)
as its O(n) when you can avoid using those methods As when using them you basically get n + n + n which isn't that great