Question 1 a) Given an array of integers of any size, n 2 1, write an algorithm
ID: 3871270 • Letter: Q
Question
Question 1 a) Given an array of integers of any size, n 2 1, write an algorithm as a pseudo code (not a program!) that would reverse every two consecutive elements of the left half of the array (i.e. reverse elements at index 0 &1, at index 2 & 3, etc.). Additionally, for the right half of the array, the algorithm must change the second element of every two consecutive elements to have to the sum of the two elements. For instance, if the right half starts at index 14, and the values at index 14 & 15 are 72 and 11, then the value at index 15 is changed to 83. If the given array is of an odd size, then the exact middle element should not be manipulated by the algorithm in any way. Finally, your algorithm must use the smallest auxiliary/additional storage to perform what is needed. b) What is the time complexity of your algorithm, in terms of Big-O? c) What is the space complexity of your algorithm, in terms of Big-O?Explanation / Answer
Solution:
Algorithm (arr, n, left, right)
1. mid = ceil ((left + right) / 2)
2. for (i = 0 ; i< mid-1; i = i +2) // process the left subarray
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1]= temp
3. if( n%2 !=0) // To make sure that middle element is untouched in case of odd length arrays
k= mid +1
else
k = mid
4. for (j=k+1; j<n; j = j+2) // process the right sub-array
arr[j] = arr[j] + arr[j-1]
Time Complexity: Since the algorithm makes one pass through the array, the time complexity is O(n).
Space Complexity: Since we use constant number of variables for auxiliary storage (like temp,mid etc.), the space complexity of algorithm is O(1).
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.