What is Arrays in DSA ???
Arrays in DSA: – Arrays are the fundamental Data Structure in computer science field, which is mainly essential for storing and accessing data in sequential manner. An array is a collection of elements, each identified by an index or a key. They are widely used due to their simplicity and the ability to quickly access element.
Importance of Arrays in DSA
1. Direct Access
Arrays allows direct access to elements using their index, enabling O(1) time complexity for read operations.
2. Memory Management
Arrays are stored in contiguous memory locations, which enhances cache performance and efficient memory utilization.
3. Fixed Size
Arrays have a predefined size, making them suitable for scenarios where the number of elements is known in advance.
4. Ease of Traversal
Iterating through array elements is straightforward due to their sequential storage.
5. Foundation for other Data Structure
Arrays are the building blocks for more complex Data Structure like lists, stacks, queues, and matrices.
Example: –
we have initial Array
[5, 1, 4, 2, 8]
1. First Pass: –
- First, Compare 5 and 1, swap to get [1, 5, 4, 2, 8]
- Second, Compare the 5 and 4, swap to get [1, 4, 5, 2, 8]
- Third, Compare the 5 and 2, swap to get [1, 4, 2, 5, 8]
- Fourth, Compare 5 and 8, no swap needed.
2. Second Pass: –
- Here First Compare the 1 and 4, no swap needed.
- Then Second Compare the 4 and 2, swap to get [1, 2, 4, 5, 8]
- Remaining elements are already in order.