![]() |
An array is a linear data structure. In an array, the operation to fetch a value takes constant time i.e., O(1). Let us see why is it so. Why the complexity of fetching value is O(1)? As Arrays are allocated contiguously in memory, Fetching a value via an index of the array is an arithmetic operation. All arithmetic operations are done in constant time i.e., O(1). Explanation: In an array, we have the memory address of index 0 (Base address). By adding the product of the index number (of value to be fetched) and the size of one element (ex. int size is 4 bytes) with the base address, we can have the address of that index’s value. we don’t have to iterate through the array. So it’s done in O(1).
Example: ![]() Memory Allocation In Array In array A[] = {8, 6, 7, 13, 8, 19} To fetch the value at index 4, we need the memory address where the value of that index is stored. The address can be obtained by doing an arithmetic operation i.e.
For more details, please refer: |
Reffered: https://www.geeksforgeeks.org
Data Structures |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 11 |