Java Data Structures and Algorithms
Data Structures and Algorithms in Java: A Guided Lesson
Why Data Structures and Algorithms Matter
A computer program does more than store information and carry out instructions. It must also organize information so that its operations—such as finding, adding, removing, or arranging data—can be performed effectively.
Data is information a program needs to store or process. A data structure is a way of organizing that data. An algorithm is a sequence of steps for solving a problem.
The choice of data structure affects how an algorithm behaves. For example, one structure may make it quick to find an item, while another may make it easier to insert or remove items. Each choice also affects how much memory is used.
A common way to describe an algorithm’s efficiency is with time complexity, which estimates how its running time grows as the amount of input grows. Space complexity describes how its memory use grows. Big-O notation expresses these growth patterns:
- O(1) describes an operation whose cost stays roughly constant as the input grows.
- O(n) describes work that grows in proportion to the number of items.
- O(logn) describes work that grows much more slowly than the number of items.
- O(n2) describes work that can grow in proportion to the square of the number of items.
These measures help programmers compare approaches. An algorithm that examines every item in a collection may take O(n) time, while one that repeatedly cuts a sorted search area in half can take O(logn) time.
The right data structure can make an algorithm more efficient because the way data is organized determines how easily the program can perform its operations.
Think About It: If a program frequently adds and removes items, would a fixed-size array or a linked list seem more suitable? The answer depends on how those operations are performed and what trade-offs matter most.
Linear and Nonlinear Data Structures
Data structures are often grouped into two broad categories.
A linear data structure arranges elements in a sequence. Each element has a position in relation to the others. Arrays, linked lists, stacks, and queues are examples. A sequence can be thought of as a row of items, although its elements do not always occupy adjacent memory locations.
A nonlinear data structure arranges data in relationships that branch or connect in more complex ways. Trees and graphs are examples. In a tree, data is organized hierarchically. In a graph, connections can link many vertices in flexible patterns.
The distinction matters because different arrangements make different tasks natural. A queue is suited to processing items in arrival order; a tree can represent hierarchy; a graph can represent a network of relationships.
Arrays
An array stores a fixed number of elements of the same data type. Its elements are accessed by index, with Java indexing beginning at 0.
For example, in an array with six elements, valid indexes are 0 through 5. The first element is at index 0, the second at index 1, and so on. This convention reflects how an element’s position is calculated relative to the start of the array: the element at index 0 is at the start, and each increase in index moves forward by one element.
In Java, a one-dimensional integer array can be declared and created like this:
int[] numbers = new int[6];
The array has space for six integers. Its length is available through numbers.length. Values can be assigned by index:
numbers[0] = 1;
numbers[1] = 2;
An array can also be initialized with values directly:
int[] values = {6, 2, 9, 1};
Access, search, and modification
Arrays have an important strength: accessing an element by index takes constant time, O(1). The program can use the index to go directly to the requested position rather than checking the preceding elements.
Searching an unsorted array for a particular value is different. A simple search examines items one at a time until it finds the target or reaches the end. In the worst case, this takes O(n) time.
Insertion and deletion can also be inconvenient. Inserting an item in the middle may require shifting later elements to make room. Deleting an item may require shifting following elements to close the gap. If the array is already full, it cannot simply grow; a larger array must be created and the elements copied into it.
Arrays therefore work well when the number of elements is known and quick indexed access is important. Their fixed capacity and shifting requirements can be disadvantages when the collection changes frequently.
Two-dimensional arrays
A two-dimensional array organizes values by rows and columns, like a table or matrix. It is accessed with two indexes: one for a row and one for a column.
int[][] table = new int[3][4];
table[0][0] = 1;
A nested loop can visit every element. The outer loop can move through rows, while the inner loop moves through the columns in each row:
for (int row = 0; row < table.length; row++) {
for (int column = 0; column < table[row].length; column++) {
System.out.println(table[row][column]);
}
}
Java represents a two-dimensional array as an array whose elements are themselves arrays. This structure is useful for grids, tables, and matrix-like data.
Sorting and searching arrays in Java
Java provides sorting utilities in the java.util.Arrays class. For example:
import java.util.Arrays;
int[] values = {6, 3, 9, 2};
Arrays.sort(values);
After sorting, the values are in ascending order. A program can then use a search method designed for sorted arrays, or implement binary search itself.
A linear search is straightforward:
static int linearSearch(int[] values, int key) {
for (int i = 0; i < values.length; i++) {
if (values[i] == key) {
return i;
}
}
return -1;
}
The method returns the matching index, or −1 if the value is absent.
Think About It: An array’s index provides fast access to a known position, but finding an unknown value in an unsorted array may still require checking many positions. Why are those two operations different?
Stacks
A stack is a linear data structure that follows last in, first out, often abbreviated as LIFO. The last element added is the first one removed.
A stack of plates illustrates the rule: a new plate is placed on top, and the top plate is removed first. The elements underneath cannot be removed directly without first removing the items above them.
The main stack operations are:
- Push: add an element to the top.
- Pop: remove and return the top element.
- Peek: examine the top element without removing it.
- Check emptiness: determine whether the stack contains any elements.
With an array implementation, a variable such as top tracks the index of the top element. A push updates the top position and stores the new value. A pop returns the top value and moves the top position down. These operations typically take O(1) time when capacity is available; a dynamically resizing implementation may occasionally need to resize.
Java has a Stack class, but modern Java code commonly uses a Deque for stack behavior:
import java.util.ArrayDeque;
import java.util.Deque;
Deque<Integer> stack = new ArrayDeque<>();
stack.push(4);
stack.push(9);
int top = stack.peek(); // 9
int removed = stack.pop(); // 9
Stacks appear in several important situations:
- Recursion: Java keeps track of active method calls using a call stack. Each call must retain information about where it should continue after a deeper call finishes.
- Undo and redo: An application can store earlier actions so that the most recent action can be reversed first.
- Browser navigation: A history structure can support returning through previously visited pages.
- Expression processing: Stacks are useful when parsing and evaluating expressions.
The restricted access is both a strength and a limitation. The top is easy to access, but an arbitrary element in the middle is not.
Queues
A queue is a linear data structure that follows first in, first out, or FIFO. The first element added is the first one removed. A line of people waiting for tickets is a familiar example: newcomers join at the back, while the person at the front is served next.
A queue tracks two ends:
- The front identifies the next element to be removed.
- The rear identifies where a new element is added.
The main operations are:
- Enqueue: add an element at the rear.
- Dequeue: remove an element from the front.
- Peek at the front: inspect the next element without removing it.
- Peek at the rear: inspect the most recently added element.
- Check emptiness and size: determine whether the queue has elements and how many it contains.
With a suitable implementation, adding and removing at the ends take O(1) time. A simple array-based queue can waste space after repeated removals if it only moves the front forward. A circular queue addresses this by treating the array as a ring: when an index reaches the array’s end, it can continue from the beginning if space is available.
Java’s Queue interface can be implemented by classes such as LinkedList or ArrayDeque. Typical queue operations include offer to add, poll to remove, and peek to inspect the front.
Queues are useful wherever tasks should be handled in arrival order. Examples include operating-system scheduling, processing waiting tasks, managing playlists, and handling pending events or interrupts.
Think About It: A stack and a queue both restrict where items are added and removed. Which one would best model a line at a ticket counter, and which one would best model a stack of plates?
Linked Lists
A linked list is a sequence of nodes. Each node contains data and a reference, or link, to another node. Unlike an array, the nodes do not need to occupy adjacent memory locations. This allows a linked list to use separate available memory locations and connect them through references.
In a singly linked list, each node points to the next node. The first node is the head; the final node usually points to null. Keeping track of the head is essential: without it, the list’s starting point—and therefore access to the chain—may be lost.
A doubly linked list stores a link to both the next node and the previous node. This makes traversal possible in both directions, at the cost of storing an additional reference.
A circular linked list connects its final node back to an earlier node, commonly the head. In a circular singly linked list, the final node points to the head rather than to null. A circular doubly linked list can link its ends in both directions.
Operations and trade-offs
Inserting or deleting a node can be efficient when the relevant location is already known: the program changes a small number of links rather than shifting many elements. However, reaching a particular position usually requires traversing the list node by node. Direct random access by index is not a linked list’s strength.
A linked list can grow or shrink as needed, so it avoids an array’s fixed-capacity limitation. It also avoids requiring one contiguous block of memory. In exchange, each node needs extra memory for its link or links, and accessing the ith element generally takes O(n) time.
Java’s LinkedList class offers methods such as addFirst, addLast, removeFirst, and removeLast. A list can be traversed with an iterator or a loop. Searching for a value with a method such as contains requires checking elements and can take O(n) time.
A linked list is useful when insertions and deletions are frequent and the locations are readily available. An array is generally more convenient when rapid access by index is the priority.
Trees and Binary Search Trees
A tree is a nonlinear structure that organizes data hierarchically. It consists of nodes connected by edges.
The top node is the root. A node connected below another node is its child; the node above it is its parent. Nodes with the same parent are siblings. A node with no children is a leaf. A tree can also contain subtrees, which are smaller trees rooted at one of its nodes.
Trees model hierarchical information such as folders and files or organizational structures. Unlike a linear sequence, a tree can branch into multiple paths.
Binary trees
A binary tree is a tree in which each node has at most two children: a left child and a right child. A node can have no children, one child, or two.
A binary tree does not necessarily impose a rule about which values belong on which side. A binary search tree (BST) adds such a rule: values smaller than a node’s value are placed in its left subtree, and values greater than it are placed in its right subtree. The rule applies throughout the subtrees, not just to a node’s immediate children.
This ordering can speed up searching. At each node, the search compares the target with the current value and chooses the left or right subtree. When the tree is reasonably balanced, the search can take about O(logn) time. If the tree becomes very unbalanced, its performance can approach O(n).
A BST supports insertion, search, deletion, and traversal. In deletion, the number of children matters:
- A leaf can be removed directly.
- A node with one child can be replaced by its child.
- A node with two children needs a replacement value that preserves the BST ordering, commonly the next value in sorted order or the previous value in sorted order.
Balanced tree designs, including AVL trees and red-black trees, add rules that limit how unbalanced a tree can become.
Traversing a binary tree
A traversal visits the tree’s nodes in a defined order. Three common depth-first traversals are preorder, inorder, and postorder.
- Preorder: visit the root, then the left subtree, then the right subtree.
- Inorder: visit the left subtree, then the root, then the right subtree.
- Postorder: visit the left subtree, then the right subtree, then the root.
For a BST, inorder traversal produces values in ascending order because the left subtree contains smaller values and the right subtree contains larger values.
Traversal order also matters for other tasks. Preorder can be useful when recording a tree’s structure or producing prefix notation for an expression tree. Postorder visits children before their parent, which can help when deleting a tree or producing postfix notation.
A recursive preorder traversal can be expressed in Java as follows:
static void preorder(Node node) {
if (node == null) {
return;
}
System.out.println(node.value);
preorder(node.left);
preorder(node.right);
}
The null check is the base case: it stops the traversal when a branch has no node. Each recursive call handles a subtree using the same rule.
Think About It: Why does inorder traversal of a BST produce values in sorted order, while a traversal of an ordinary binary tree does not necessarily do so?
Algorithms, Complexity, and Choosing an Approach
An algorithm is a step-by-step procedure for solving a problem. A good algorithm addresses the problem correctly and uses resources appropriately. The same problem can often be solved by different algorithms, so analysis helps determine which approach is suitable.
Time and space are separate concerns. An algorithm may save time by using additional memory, or save memory while doing more work. This is a time–space trade-off.
Analysis often considers three cases:
- The best case describes the most favorable input.
- The average case describes typical performance under stated assumptions.
- The worst case describes the greatest work an input of a given size may require.
Worst-case analysis is useful because it provides an upper bound on the work an algorithm may need. For example, a linear search may find its target immediately, but if the target is at the end—or absent—it may inspect all n elements.
Reasoning about loops
A loop that visits each of n items once usually takes O(n) time. A loop inside another loop may take O(n2) time if both loops each run about n times. Sequential sections contribute their costs, but Big-O notation retains the dominant growth term. For example, O(n2+n) simplifies to O(n2) because the quadratic term grows faster as n increases.
Recursive algorithms require additional care. Each recursive call may use call-stack memory. Recursion can make a solution clearer, especially for trees, but it can also use more space than an iterative approach.
Think About It: If two algorithms solve the same problem, what information about their running time and memory use would help determine which one is the better choice?
Searching Algorithms
Linear search
Linear search examines elements one at a time until it finds the target or reaches the end. It can be used whether or not the data is sorted.
Its worst-case time complexity is O(n) because every element may need to be examined. Its extra space use can be O(1) when the search only uses a small, fixed number of variables.
Linear search is simple and useful for small or unsorted collections. It is also a reasonable choice when the collection is searched only occasionally.
Binary search
Binary search repeatedly halves the search range. It requires the data to be sorted according to the same ordering used by the comparisons.
The method compares the target with the middle element:
- If they match, the search succeeds.
- If the target is smaller, the search continues in the lower half.
- If the target is larger, the search continues in the upper half.
Because each comparison removes about half of the remaining possibilities, binary search takes O(logn) time in the worst case. An iterative implementation uses O(1) extra space; a recursive implementation uses call-stack space, typically O(logn).
The sorted-data requirement is crucial. Applying binary search to an unsorted collection can cause the algorithm to discard the half that contains the target.
static int binarySearch(int[] values, int key) {
int low = 0;
int high = values.length - 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (values[mid] == key) {
return mid;
} else if (values[mid] < key) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
The method returns the index when the target is found and −1 when it is absent.
Greedy Algorithms and Dynamic Programming
A greedy algorithm makes a locally attractive choice at each step. It chooses what appears to be the best option at that moment, then continues from there.
A greedy choice may produce a feasible solution without producing the best overall solution. Consider a route problem with two possible paths from a starting city to a destination. A greedy method might choose the next city that is closest or quickest to reach locally. That choice may later lead to a longer total journey than another initial choice.
Greedy algorithms are effective when local choices are guaranteed to lead to a globally optimal answer for the problem being solved. They are used in problems involving spanning trees and in certain selection problems. They are not automatically correct for every optimization problem.
Dynamic programming is another approach to solving problems with smaller subproblems. It records solutions to subproblems so that they can be reused. Unlike a purely greedy method, dynamic programming can compare alternative choices and combine subproblem results to find an overall optimum. It often uses more memory for the stored results.
The key contrast is that a greedy algorithm commits to a locally preferred choice, while dynamic programming retains and uses relevant subproblem solutions to reason about the overall result.
Fractional knapsack
The fractional knapsack problem asks which items should be selected to maximize total profit while staying within a weight limit. Unlike the zero–one knapsack problem, the fractional version permits taking part of an item.
For each item, the algorithm calculates its profit per unit of weight:
ratio=weightprofitIt then considers items in descending order of that ratio, taking as much as possible of each until the capacity is filled. If only part of the final item fits, the remaining fraction can be taken.
This greedy strategy works for the fractional version because an item can be divided. A high profit-to-weight ratio gives more profit for each unit of capacity. This reasoning does not automatically solve the zero–one version, where items cannot be split.
Sorting Algorithms: Merge Sort and Quicksort
Sorting places values into a chosen order, such as ascending or descending order. Sorted data can make later tasks, including searching, more efficient.
Merge sort
Merge sort follows the divide-and-conquer approach:
- Divide the collection into smaller parts.
- Continue dividing until each part contains one element.
- Merge the parts back together in sorted order.
A one-element collection is already sorted. During merging, the algorithm compares the first unprocessed element of each sorted part, copies the smaller one into the result, and continues. If one part is exhausted, the remaining elements from the other part are copied across.
Merge sort takes O(nlogn) time in its usual implementations. It is stable when equal values retain their original relative order. The common array-based implementation uses O(n) additional space for merging.
Quicksort
Quicksort also uses divide and conquer, but it divides the collection through partitioning:
- Choose a value called the pivot.
- Rearrange values so that those smaller than the pivot are on one side and those larger are on the other.
- Place the pivot in its final sorted position.
- Recursively sort the sections on each side.
The pivot’s final position divides the problem into smaller problems. A partition that divides the data fairly evenly leads to average time complexity of O(nlogn). Poorly balanced partitions can produce worst-case time complexity of O(n2).
Quicksort is typically performed in place, using relatively little extra storage apart from recursion. Unlike stable merge sort, standard quicksort implementations are generally not stable. Its performance depends in part on pivot selection and how balanced the partitions are.
Think About It: Merge sort and quicksort both divide a problem into smaller parts. What is the main difference between how they create those parts?
Graphs
A graph represents objects and the connections between them. The objects are called vertices (or nodes), and the connections are called edges.
Graphs can represent friendships, routes between cities, or other networks of relationships. An edge between two vertices indicates that a connection exists; in some graphs, it can also carry information such as a distance or cost.
Common graph categories include:
- A directed graph, where each edge has a direction. A connection from one vertex to another does not necessarily imply a connection back.
- An undirected graph, where an edge represents a two-way connection.
- A connected graph, where every vertex can be reached from every other vertex by following edges.
- A disconnected graph, where some vertices or groups cannot be reached from others.
- An isolated vertex, which has no connecting edges.
Graph representations
An adjacency matrix uses a two-dimensional table. Each row and column represents a vertex. An entry records whether an edge connects the pair of vertices; a common representation uses 1 for an edge and 0 for no edge. The matrix gives direct access to the connection status of a pair, but it uses space proportional to V2, where V is the number of vertices.
An adjacency list stores, for each vertex, a list of the vertices connected to it. It is often more space-efficient for a sparse graph, where relatively few possible edges exist. In Java, an adjacency list can be represented with a list of lists.
The choice between these representations depends on the graph and the operations the program needs. A matrix makes checking a particular edge straightforward; an adjacency list makes it natural to visit a vertex’s neighbors.
Breadth-first search
Breadth-first search (BFS) visits vertices level by level, exploring nearby vertices before moving farther away. It uses a queue:
- Add the starting vertex to the queue and mark it visited.
- Remove the front vertex from the queue.
- Add each unvisited neighbor to the back of the queue and mark it visited.
- Continue until the queue is empty.
Marking a vertex when it is added prevents the algorithm from repeatedly adding it when multiple edges lead to it. BFS is useful for exploring a graph in increasing distance by number of edges from the starting vertex.
With an adjacency list, BFS takes O(V+E) time, where E is the number of edges, because each vertex and edge is examined a bounded number of times.
Depth-first search
Depth-first search (DFS) follows one path as far as possible before returning to explore another path. It can be implemented with recursion or an explicit stack:
- Visit the starting vertex and mark it visited.
- Choose an unvisited neighbor and continue from there.
- When no unvisited neighbor remains, backtrack to an earlier vertex.
- Continue until every reachable vertex has been visited.
A stack or the recursive call stack holds the path being explored. As with BFS, marking vertices as visited prevents repeated exploration. With an adjacency list, DFS also takes O(V+E) time.
A simplified recursive Java pattern is:
static void dfs(int vertex, List<List<Integer>> graph, boolean[] visited) {
visited[vertex] = true;
System.out.println(vertex);
for (int neighbor : graph.get(vertex)) {
if (!visited[neighbor]) {
dfs(neighbor, graph, visited);
}
}
}
BFS and DFS differ chiefly in their exploration order and supporting structure: BFS uses a queue and explores broadly; DFS uses a stack or recursion and explores deeply before backtracking.
Spanning trees and minimum spanning trees
A spanning tree connects every vertex of a connected graph without forming a cycle. If a graph has V vertices, a spanning tree has V−1 edges. A graph can have more than one spanning tree.
A minimum spanning tree is a spanning tree whose total edge weight is as small as possible. This is useful when connections have costs, such as distances or construction costs.
Two common algorithms for finding a minimum spanning tree are Prim’s algorithm and Kruskal’s algorithm:
- Prim’s algorithm starts from a vertex and repeatedly adds a lowest-weight edge that connects the growing tree to a vertex not yet in it. The selected edges must not create a cycle.
- Kruskal’s algorithm considers edges in increasing order of weight and adds an edge when doing so does not create a cycle. It stops when all vertices are connected.
Both methods seek a spanning tree with minimum total edge weight, but they build it differently. Prim’s grows one connected tree outward; Kruskal’s selects edges globally while joining components.
Recursion and Backtracking
Recursion occurs when a method calls itself to solve a smaller instance of a problem. A recursive solution needs a base case, which stops further calls, and a recursive step, which moves the problem toward that base case.
Tree traversals are natural examples: a traversal handles a node, then calls itself on a smaller subtree. Recursion can make such algorithms concise, but every active call uses call-stack space.
Backtracking explores possible choices and reverses a choice when it leads to a dead end or an unsuitable result. It is useful for problems where several possible paths or arrangements must be considered.
A maze illustrates the method. At each position, an algorithm can try a permitted move. It marks the position as visited, explores a possible route, and returns to an earlier position if that route cannot reach the goal. It then tries another available route. A visited structure helps prevent the search from looping through the same positions repeatedly.
Backtracking can be described as “choose, explore, and undo.” The undo step restores the state so that another option can be explored. In some problems, backtracking may explore many possibilities, so pruning paths that cannot lead to a valid solution can be important.
Comprehensive Review
Data structures organize information so that programs can use it effectively. Arrays provide fast access by index but have fixed capacity and can require shifting during insertion or deletion. Linked lists can grow dynamically and change links efficiently, but accessing a particular position usually requires traversal. Stacks enforce last-in, first-out behavior, while queues enforce first-in, first-out behavior.
Trees organize data hierarchically. A BST uses an ordering rule to guide insertion and search, and its inorder traversal produces sorted values. Graphs represent more general relationships through vertices and edges. BFS explores a graph level by level using a queue; DFS follows paths deeply using a stack or recursion. Spanning-tree algorithms connect vertices without cycles, while minimum spanning trees minimize total edge weight.
Algorithms determine how operations are performed. Linear search checks items one by one; binary search repeatedly halves a sorted search range. Merge sort divides and merges, while quicksort partitions around a pivot. Greedy algorithms make locally attractive choices, whereas dynamic programming uses solutions to subproblems to guide an overall solution. Recursion solves problems through smaller instances, and backtracking explores alternatives while undoing choices that do not work.
The central design question is always how the organization of data and the steps of an algorithm affect time, memory, and correctness. A solution is effective when its structure and algorithm fit the problem’s required operations and constraints.

Ask anything
We've read this whole study set, so questions about it get the best answers.