reverseArray3.js (*** Two Pointer Approach***)
/* Reverse of an Array by two pointer approach
Given
A =[5,8,7,3,10]
Output
A=[10,3,7,8,5]
*/
/////////////////////////////////////////////////////////////////////////////////////////////////////////
//index 0 1 2 3 4
let A = [5, 8, 7, 3, 10];
let p = 0; // intialising while loop
let q = A.length - 1; //intialising while loop i.e 4
while (p < q) // 1) p =0 < q=4 true , 2) p=1 < q=3 true , etc....
{
let temp = A[p]; // 1) temp = 5 , 2) temp = 8
A[p] = A[q]; // 1) A[p]= 10 , 2) A[p]= 3
A[q] = temp; // 1) A[q]= 5 , 2) A[q]= 8
p++ //increment of while loop , 1)p=1 2) p=2 etc...
q-- //decrement of while loop , 1) q=3 2) q= 2 etc...
}
console.log(A);
T.C= o(n/2)
= o(n)
S.C = o(1)
//////////////////////////////////////////////////////////////////////////////////////////////
TERMINAL:

Comments
Post a Comment