Monday, July 4, 2022
HomeSoftware DevelopmentWhy does accessing an Array factor take O(1) time?

Why does accessing an Array factor take O(1) time?


View Dialogue

Enhance Article

Save Article

Like Article

An array is a linear knowledge construction. In an array, the operation to fetch a price takes fixed time i.e., O(1).  Allow us to see why is it so.

Why the complexity of fetching worth is O(1)?

As Arrays are allotted contiguously in reminiscence, Fetching a price by way of an index of the array is an arithmetic operation. All arithmetic operations are performed in fixed time i.e., O(1).

Clarification:

In an array, now we have the reminiscence tackle of index 0 (Base tackle). By including the product of the index quantity (of worth to be fetched) and the scale of 1 factor (ex. int measurement is 4 bytes) with the bottom tackle, we will have the tackle of that index’s worth. we don’t need to iterate via the array. So it’s performed in O(1).

Handle of ith Index = Base tackle + offset = Handle of 0th Index + i × (measurement of 1 factor)

Instance:

Reminiscence Allocation In Array

In array A[] = {8, 6, 7, 13, 8, 19}

To fetch the worth at index 4, we’d like the reminiscence tackle the place the worth of that index is saved. The tackle could be obtained by doing an arithmetic operation i.e.

Handle of worth at index 4 = Handle of index 0’s worth + 4 × measurement of int = 108 + 4 × 4 bytes
Handle of worth at index 4 = 124
A[4] = worth at tackle 124 = 8

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments