Data structure algorithms in Java

Category : Java | Sub Category : Java Programs from Coding Interviews | By Prasad Bonam Last updated: 2023-07-10 04:35:48 Viewed : 359


Here are some commonly used data structure algorithms in Java with code examples:

  1. Binary Search: Binary search is an algorithm for finding a specific target value within a sorted array. It compares the target value with the middle element of the array and recursively narrows down the search range.
java
public static int binarySearch(int[] arr, int target) { int left = 0; int right = arr.length - 1; while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; // Target not found }
  1. Bubble Sort: Bubble sort is a simple comparison-based sorting algorithm. It repeatedly swaps adjacent elements if they are in the wrong order until the entire array is sorted.
java
public static void bubbleSort(int[] arr) { int n = arr.length; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } }
  1. Depth-First Search (DFS): DFS is an algorithm for traversing or searching tree or graph data structures. It explores as far as possible along each branch before backtracking.
java
public class Graph { private int vertices; private LinkedList<Integer>[] adjacencyList; // ... public void DFS(int startVertex) { boolean[] visited = new boolean[vertices]; DFSUtil(startVertex, visited); } private void DFSUtil(int vertex, boolean[] visited) { visited[vertex] = true; System.out.print(vertex + " "); for (Integer neighbor : adjacencyList[vertex]) { if (!visited[neighbor]) { DFSUtil(neighbor, visited); } } } }

These are just a few examples of data structure algorithms in Java. Java provides a rich set of libraries and APIs for various data structures and algorithms. You can explore more algorithms such as sorting (e.g., QuickSort, MergeSort), graph algorithms (e.g., Breadth-First Search, Dijkstras algorithm), and more based on your specific requirements and use cases.

Search
Related Articles

Leave a Comment: