template <typename T>
void reverseVector(vector<T> &vec, int start, int end) {
if(start < end) {
char temp = vec[start];
vec[start] = vec[end];
vec[end] = temp;
reverseVector(vec, start + 1, end – 1); }
}
}
Assuming N = vec.size() what would be the time complexity of this method?
Assuming I am correct, a getting and setting a vector has time O(1). Thus, the first 3 lines in the if statement are all O(1) each. Then, the method recursively calls itself and each time the function becomes smaller, iterating n(n-1)(n-2)... times. So my answer would be O(n!) for this method. Am I correct?
edit: similar syntax, but with linked list
template <typename T>
void reverseLinkedList(list<T> &lst, int start, int end) {
if(start < end) {
char temp = lst[start];
lst[start] = lst[end];
lst[end] = temp;
reverseLinkedList(lst, start + 1, end – 1);
}
}
That is O(n)
.
You swap elements n/2
times: (0 with n-1), (1 with n-2), ... (n/2 - 1 with n/2 + 1)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.