Unit 2: Introduction to Array Concepts
I. Orientation — Linear Data Structures
A linear data structure organizes elements sequentially so that, except at the ends, each element has a predecessor and a successor. Arrays, stacks, and queues are linear structures, but they differ in memory organization and rules for accessing data.
- Element: A single stored value, such as
25in an integer array. - Index: An integer position used to access an array element; zero-based indexing numbers positions from
0ton - 1. - Capacity: The maximum number of elements that allocated storage can hold.
- Logical size: The number of elements currently stored; it may be smaller than the capacity.
- Contiguous storage: Array elements occupy consecutive memory locations.
- Abstract data type (ADT): A structure defined by its permitted values and operations; stacks and queues are ADTs that can be implemented using arrays.
- Complexity convention: Time and auxiliary space are expressed using Big-O notation, such as
O(n), wherenis the input size.
II. Arrays — Indexed Contiguous Storage
An array is a fixed-capacity collection of same-type elements stored contiguously and accessed by index. Direct indexing is fast, but inserting or deleting within the sequence may require shifting elements.
A. Definition and initialization of arrays
Array initialization allocates indexed storage and may assign initial values to its elements.
- Declaration: A declaration specifies the element type, name, and capacity;
int A[5]reserves space for five integers in C-like notation. - Initialization: Values may be supplied when the array is created.
A = [12, 7, 19, 4, 10]- Index range: For an array of length
n = 5, valid indices are0through4; therefore,A[2] = 19. - Homogeneity: A conventional array stores values of one declared type, so every element has the same storage size.
- Boundary rule: Accessing an index below
0or at leastnis out of bounds and may cause an error or undefined behavior, depending on the language.
B. Memory representation of one-dimensional arrays
A one-dimensional array maps each index to a memory address using a constant-size offset.
- Address formula:
Address(A[i]) = B + i × w- Symbols:
A[i]is the element at zero-based indexi.Bis the base address ofA[0].wis the number of bytes occupied by one element.
- Example: If
B = 1000,w = 4bytes, andi = 3, thenAddress(A[3]) = 1000 + 3 × 4 = 1012. - Consequence: Because the address is calculated directly, indexed access takes
O(1)time. - Locality: Adjacent elements are close in memory, often improving cache performance during sequential processing.
C. Array traversal
Array traversal visits each logical element, usually from the first index to the last.
- Procedure:
for i ← 0 to n - 1
process(A[i])- Symbols:
iis the current index,nis the logical size, andprocessrepresents an operation such as printing or summing. - Coverage: The loop processes exactly
nelements, includingA[0]andA[n - 1]. - Complexity: A complete traversal takes
O(n)time andO(1)auxiliary space when no additional collection is created.
D. Array insertion
Insertion places a value at a chosen index while preserving the order of existing elements.
- Preconditions: The insertion index
pmust satisfy0 ≤ p ≤ n, and the capacityCmust satisfyn < C. - Procedure:
for i ← n - 1 downto p
A[i + 1] ← A[i]
A[p] ← x
n ← n + 1- Symbols:
pis the insertion index,xis the new value,nis the old logical size, andCis capacity. - Direction: Elements shift from right to left in the loop so that an unread value is not overwritten.
- Complexity: Insertion at the end is
O(1)when capacity exists; insertion at the beginning or middle isO(n)because up tonvalues move.
E. Array deletion
Deletion removes the element at a specified index and closes the resulting gap.
- Precondition: The deletion index
pmust satisfy0 ≤ p < n. - Procedure:
removed ← A[p]
for i ← p to n - 2
A[i] ← A[i + 1]
n ← n - 1- Symbols:
removedstores the deleted value,pis its index, andnis the old logical size. - Logical effect: The capacity is unchanged, but the logical size decreases by one.
- Complexity: Deleting the last element is
O(1); deleting near the beginning isO(n)because later elements shift left.
III. Array Searching — Locating a Target Value
Searching determines whether a target occurs in an array and commonly returns its index or a failure indicator such as -1.
A. Linear search
Linear search compares the target with elements sequentially and does not require sorted data.
- Procedure:
for i ← 0 to n - 1
if A[i] = x
return i
return -1- Symbols:
xis the target,iis the examined index, and-1means that no match was found. - Behavior: In
[8, 3, 11, 6], searching for11checks indices0,1, and2, then returns2. - Complexity: The best case is
O(1)when the first element matches; average and worst cases areO(n). - Use: It is appropriate for small, unsorted arrays or searches performed too rarely to justify sorting.
B. Binary search
Binary search repeatedly halves the search interval and therefore requires an array sorted by the same ordering used in comparisons.
- Procedure:
low ← 0
high ← n - 1
while low ≤ high
mid ← low + floor((high - low) / 2)
if A[mid] = x
return mid
else if A[mid] < x
low ← mid + 1
else
high ← mid - 1
return -1- Symbols:
lowandhighbound the active interval,midis its midpoint, andfloordiscards the fractional part. - Elimination rule: If
A[mid] < x, all indices throughmidare discarded; otherwise, the upper half is discarded. - Complexity: The best case is
O(1), while average and worst cases areO(log n); iterative auxiliary space isO(1).
IV. Sorting and Efficiency — Ordering and Measuring Operations
Sorting rearranges values into a defined order, while complexity analysis describes how resource use grows as the input becomes larger.
A. Bubble sort
Bubble sort repeatedly compares adjacent elements and swaps inverted pairs, causing a largest unsorted value to move toward the end after each pass.
- Procedure:
for pass ← 0 to n - 2
swapped ← false
for j ← 0 to n - 2 - pass
if A[j] > A[j + 1]
swap A[j], A[j + 1]
swapped ← true
if swapped = false
break- Symbols:
passcounts completed passes,jindexes adjacent pairs, andswappedrecords whether a change occurred. - Invariant: After each full pass, one more element at the right is in its final sorted position.
- Properties: Bubble sort is in-place with
O(1)auxiliary space and stable when only strictly inverted pairs are swapped. - Complexity: With early termination, an already sorted array takes
O(n)time; average and worst cases takeO(n²).
B. Complexity analysis of array operations
Complexity analysis compares operations by their growth rate rather than by machine-dependent execution time.
- Direct access: Reading or updating
A[i]isO(1)because one address calculation identifies the element. - Traversal and linear search: Visiting up to
nelements takesO(n). - Binary search: Halving the remaining interval gives
O(log n)search time, provided the array is sorted. - Insertion and deletion: End operations can be
O(1), but position-based operations areO(n)in the worst case because of shifting. - Bubble sort: Nested comparisons produce
O(n²)average and worst-case time. - Space distinction: The array itself uses
O(n)storage; an algorithm using only counters and temporary values requiresO(1)auxiliary space.
V. Stacks — Last-In, First-Out Processing
A stack is a linear ADT in which insertion and deletion occur only at the top, following the last-in, first-out (LIFO) rule.
A. Definition and operations of stacks
Stack operations restrict access to the most recently added element.
- Core operations:
pushinserts,popremoves,peekreads the top, andisEmptytests whether the stack has no elements. - Array representation: An array
Sof capacityCstores values, whiletopstores the index of the current top element. - Initial state:
top = -1represents an empty stack; a stack containing one element hastop = 0. - Applications: Function-call management, undo history, expression evaluation, and bracket matching use LIFO order.
B. Stack traversal
Stack traversal visits stored elements without changing the stack’s logical state.
- Top-to-bottom procedure:
for i ← top downto 0
process(S[i])- Symbols:
Sis the stack array,topis the highest occupied index, andiis the traversal index. - Order: Top-to-bottom traversal displays elements in potential removal order.
- Complexity: Traversing
kstored elements takesO(k)time andO(1)auxiliary space.
C. Push operation
Push adds a new element at the top of a non-full stack.
- Procedure:
if top = C - 1
report overflow
else
top ← top + 1
S[top] ← x- Symbols:
Cis capacity andxis the value being inserted. - Order requirement: Incrementing
topbefore assignment selects the next free position. - Complexity: Array-based push takes
O(1)time.
D. Pop operation
Pop removes and returns the current top element.
- Procedure:
if top = -1
report underflow
else
x ← S[top]
top ← top - 1
return x- Logical removal: Decrementing
topmakes the old location inactive even if its bits remain in memory. - Complexity: Pop takes
O(1)time because no elements are shifted.
E. Stack underflow and overflow conditions
Underflow and overflow identify invalid stack operations at its two capacity boundaries.
- Underflow: Occurs when
poporpeekis attempted whiletop = -1; there is no valid element to return. - Overflow: Occurs in a fixed array implementation when
pushis attempted whiletop = C - 1; every allocated slot is occupied.- Handling: Operations should return an error, raise an exception, or report status without modifying the stack.
VI. Queues — First-In, First-Out Processing
A queue is a linear ADT in which values enter at the rear and leave from the front, following the first-in, first-out (FIFO) rule.
A. Definition and operations of queues
Queue operations preserve arrival order by separating the insertion and deletion ends.
- Core operations:
ENQinserts at the rear,DEQremoves from the front, andpeekFrontreads the oldest element. - Array representation: Array
Qhas capacityC;frontandrearidentify the first and last occupied indices. - Initial state:
front = rear = -1represents an empty queue. - Applications: Print scheduling, request handling, breadth-first search, and buffering use FIFO order.
B. Queue traversal
Queue traversal processes active elements from the front through the rear without removing them.
- Procedure:
if front ≠ -1
for i ← front to rear
process(Q[i])- Symbols:
Qis the queue array andiis the current occupied index. - Order: Traversal follows arrival order, beginning with the next element eligible for removal.
- Complexity: If
kelements are stored, traversal takesO(k)time.
C. ENQ operation
ENQ adds a value at the rear of a queue when storage is available.
- Procedure for a linear array queue:
if rear = C - 1
report overflow
else
if front = -1
front ← 0
rear ← rear + 1
Q[rear] ← x- Symbols:
xis the incoming value, andCis the array capacity. - First insertion: Setting
frontto0establishes the first active position. - Complexity: ENQ takes
O(1)time because existing elements do not move.
D. DEQ operation
DEQ removes and returns the element at the front of a non-empty queue.
- Procedure:
if front = -1
report underflow
else
x ← Q[front]
if front = rear
front ← -1
rear ← -1
else
front ← front + 1
return x- Final removal: When
front = rear, the removed value was the only element, so both markers return to the empty state. - Complexity: DEQ takes
O(1)time because the remaining elements are not shifted.
E. Queue underflow and overflow conditions
Queue boundary conditions prevent removal from an empty structure and insertion beyond allocated storage.
- Underflow: Occurs when DEQ is requested while
front = -1; no queued value exists. - Overflow: In a linear array queue, it occurs when
rear = C - 1, even if earlier positions became unused after deletions.- Limitation: This “false overflow” results from not reusing vacant leading slots; a circular queue avoids it by wrapping indices around the array.
- Handling: A failed operation must report the condition and leave
front,rear, and stored data logically unchanged.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →