time complexity for code and an order of magnitude improvement -
i have following problem:
for following code, reason, give time complexity of function.
write function performs same task order-of magnitude improvement in time complexity. function greater (time or space) complexity not credit.
code:
int something(int[] a) { (int = 0; < n; i++) if (a[i] % 2 == 0) { temp = a[i]; for(int j = i; j > 0; j--) a[j] = a[j-1]; a[0] = temp; } } i'm thinking since temp = a[i] assignment in worst case done n times, time complexity of n assigned that, , a[j] = a[j-1] run n(n+1)/2 times time complexity value of (n2+n)/2 assigned that, summing them returns time complexity of n+0.5n2+0.5n, removing constants lead 2n+n2 , complexity of n2.
for order of magnitude improvement:
int something(int[] a) { string answer = ""; (int = 0; < n; i++) { if (a[i] % 2 == 0) answer = a[i] + answer; else answer = answer + a[i]; } (int = 0; < n; i++) a[i] = answer.charat(i); } the code inside first for-loop executed n times , in second for-loop n times, summing gives time complexity figure of 2n.
is correct? or doing wrong?
i suppose function arrange list numbers @ beginning of list , followed odd numbers.
for first function complexity o(n2) have specified.
but second function complexity o(n) if operator + used appending implemented constant time operation. append operator + implemented constant time operation without hidden complexity. can conclude second operation takes o(n) time.
Comments
Post a Comment