Category : Java | Sub Category : Java Programs from Coding Interviews | By Prasad Bonam Last updated: 2023-07-10 10:05:48 Viewed : 81
Here are some commonly used data structure algorithms in Java with code examples:
javapublic 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
}
javapublic 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;
}
}
}
}
javapublic 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.