0% found this document useful (0 votes)
20 views7 pages

Java DSA Basics for Beginners

Uploaded by

sabeershaik009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views7 pages

Java DSA Basics for Beginners

Uploaded by

sabeershaik009
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Beginner-Friendly Java DSA Code

Examples with Explanation


1. Arrays
Arrays store multiple values in a single variable. You can access
each item using its index.

public class ArrayExample {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40};

// Traversing the array


for (int i = 0; i < [Link]; i++) {
[Link](numbers[i]);
}
}
}

2. Strings
Strings are sequences of characters. You can reverse them by
reading characters from the end.

public class StringExample {


public static void main(String[] args) {
String name = "Java";
String reversed = "";

for (int i = [Link]() - 1; i >= 0; i--) {


reversed += [Link](i);
}

[Link]("Reversed: " + reversed);


}
}
3. Linked List
A linked list is a sequence of nodes where each node points to
the next. It's useful for dynamic data.

class Node {
int data;
Node next;

Node(int d) {
data = d;
next = null;
}
}

public class LinkedListExample {


public static void main(String[] args) {
Node head = new Node(10);
[Link] = new Node(20);
[Link] = new Node(30);

Node temp = head;


while (temp != null) {
[Link]([Link] + " ");
temp = [Link];
}
}
}

4. Stack
A stack follows LIFO (Last In, First Out). You can push and pop
elements like a stack of plates.

import [Link];

public class StackExample {


public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();

[Link](10);
[Link](20);
[Link](30);
while (![Link]()) {
[Link]([Link]());
}
}
}

5. Queue
A queue follows FIFO (First In, First Out). Think of people
standing in line.

import [Link];
import [Link];

public class QueueExample {


public static void main(String[] args) {
Queue<Integer> queue = new LinkedList<>();

[Link](100);
[Link](200);
[Link](300);

while (![Link]()) {
[Link]([Link]());
}
}
}

6. HashMap
HashMap stores key-value pairs. Useful when you want to search
values by keys quickly.

import [Link];

public class HashMapExample {


public static void main(String[] args) {
HashMap<String, Integer> marks = new HashMap<>();
[Link]("Alice", 90);
[Link]("Bob", 80);
[Link]([Link]("Alice"));
}
}

7. Recursion
Recursion means a function calling itself. Useful for solving
problems like factorial.

public class RecursionExample {


static int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n - 1);
}

public static void main(String[] args) {


[Link](factorial(5)); // Output: 120
}
}

8. Binary Search
Binary Search finds elements in sorted arrays quickly by dividing
the array into halves.

public class BinarySearch {


public static int search(int[] arr, int key) {
int low = 0, high = [Link] - 1;

while (low <= high) {


int mid = (low + high) / 2;

if (arr[mid] == key)
return mid;
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1; // not found
}

public static void main(String[] args) {


int[] arr = {10, 20, 30, 40, 50};
[Link](search(arr, 30)); // Output: 2
}
}

9. Binary Tree (Inorder Traversal)


A binary tree has nodes with at most 2 children. Inorder
traversal visits left, root, then right.

class TreeNode {
int data;
TreeNode left, right;

TreeNode(int val) {
data = val;
left = right = null;
}
}

public class BinaryTreeExample {


public static void inorder(TreeNode root) {
if (root != null) {
inorder([Link]);
[Link]([Link] + " ");
inorder([Link]);
}
}

public static void main(String[] args) {


TreeNode root = new TreeNode(1);
[Link] = new TreeNode(2);
[Link] = new TreeNode(3);
[Link] = new TreeNode(4);

inorder(root); // Output: 4 2 1 3
}
}
10. Graph (Using Adjacency List)
A graph can be represented using adjacency list. You can store
connected nodes in a list.

import [Link].*;

public class GraphExample {


public static void main(String[] args) {
int V = 5; // Number of vertices
List<List<Integer>> adj = new ArrayList<>();

for (int i = 0; i < V; i++)


[Link](new ArrayList<>());

// Add edges
[Link](0).add(1);
[Link](0).add(2);
[Link](1).add(3);
[Link](2).add(4);

// Print adjacency list


for (int i = 0; i < V; i++) {
[Link]("Node " + i + ": ");
for (int node : [Link](i)) {
[Link](node + " ");
}
[Link]();
}
}
}

11. Bubble Sort


Bubble sort compares each pair and swaps if needed, moving the
largest to the end step-by-step.

public class BubbleSort {


public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};

for (int i = 0; i < [Link] - 1; i++) {


for (int j = 0; j < [Link] - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}

for (int num : arr) {


[Link](num + " ");
}
}
}

12. Insertion Sort


Insertion sort builds the sorted array one item at a time by
comparing and inserting elements.

public class InsertionSort {


public static void main(String[] args) {
int[] arr = {9, 5, 1, 4, 3};

for (int i = 1; i < [Link]; i++) {


int key = arr[i];
int j = i - 1;

while (j >= 0 && arr[j] > key) {


arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}

for (int num : arr) {


[Link](num + " ");
}
}
}

Common questions

Powered by AI

Recursion simplifies algorithmic problems by breaking them into smaller instances of the same problem. Calculating a factorial recursively is straightforward: the factorial of n is defined as n times the factorial of (n-1). This recursive approach closely mirrors the mathematical definition of factorial, making the code more intuitive and easier to understand.

The binary search algorithm optimizes searching by repeatedly dividing a sorted array in half, eliminating half of the elements with each comparison, which reduces the time complexity to O(log n). In contrast, a linear search checks each element one by one, resulting in a time complexity of O(n)

Inorder traversal of a binary tree processes nodes in the order: left child, root, right child. This traversal yields the nodes' values in sorted order for binary search trees. In contrast, preorder traversal processes nodes in the order: root, left child, right child, while postorder processes them in order: left child, right child, root. Each traversal order serves different algorithmic purposes, such as constructing tree structures or evaluating expressions.

A linked list is a dynamic data structure consisting of nodes where each node contains data and a reference to the next node. In contrast, an array is a fixed-size data structure where elements are indexed and stored in contiguous memory locations. Linked lists provide efficient memory usage and easier insertion and deletion operations compared to arrays, which have constant time access but can be inefficient for insertion and deletion due to the need to shift elements.

An adjacency list represents a graph by having an array of lists, where each list corresponds to the vertices adjacent to a specific vertex. This representation is space efficient for sparse graphs, as it only stores existing edges, unlike an adjacency matrix that requires space for all possible edges. The adjacency list also allows easy iteration over neighbors of a vertex, making it suitable for algorithms like DFS and BFS.

One might prefer using a HashMap for key-value storage due to its efficient average time complexity of O(1) for both insertion and lookup operations. This efficiency makes it particularly useful for applications requiring fast data retrieval by key. Additionally, HashMap allows for dynamic resizing and does not require keys to be ordered, making it flexible for various use cases.

Stacks are ideal for implementing depth-first search (DFS) due to their last-in, first-out (LIFO) order that naturally aligns with the DFS backtracking process. Using a stack allows for easy management of the nodes as you traverse down the depth of the graph and then backtrack when necessary. This backtracking is efficient because you can simply pop nodes off the stack as you backtrack.

Bubble sort functions by repeatedly stepping through the list to be sorted, comparing each pair of adjacent elements and swapping them if they are in the wrong order. This process is repeated until the list is sorted. Performance-wise, bubble sort is inefficient for large datasets with an average and worst-case time complexity of O(n^2) due to the repeated swapping of adjacent elements. It is generally suitable for educational purposes or datasets that are nearly sorted.

The choice of data structure impacts time complexity for adding and removing elements. For both stacks and queues, the time complexity for addition (push in stacks and enqueue in queues) and removal (pop in stacks and dequeue in queues) is O(1), since each operation is done at one end of the structure. However, the conceptual operations and order in which elements are added and removed differ, with stacks using LIFO and queues using FIFO order.

The insertion sort algorithm builds a sorted array by iteratively taking each element and inserting it into its proper position within the previously sorted subsection of the array. This generally involves comparing the current element to others in the sorted portion and shifting elements until the correct position is found. Its time complexity is O(n^2) in the average and worst case due to the nested loops required for elements to be compared and shifted.

You might also like