Skip to content

Commit 4fbbdff

Browse files
committed
refactor
1 parent 2246704 commit 4fbbdff

File tree

12 files changed

+988
-0
lines changed

12 files changed

+988
-0
lines changed
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Implementation
2+
3+
### Example
4+
5+
Here is a simple example of how arrays are used in C++:
6+
7+
```cpp
8+
#include <iostream>
9+
using namespace std;
10+
11+
int main() {
12+
// Declare and initialize an array
13+
int arr[5] = {1, 2, 3, 4, 5};
14+
15+
// Access elements
16+
cout << "Element at index 2: " << arr[2] << endl; // Output: 3
17+
18+
// Insert an element (inefficient)
19+
int n = 5; // Current size of the array
20+
int newArr[6];
21+
for (int i = 0; i < n; i++) {
22+
newArr[i] = arr[i];
23+
}
24+
newArr[2] = 10; // Inserting 10 at index 2
25+
for (int i = 2; i < n; i++) {
26+
newArr[i + 1] = arr[i];
27+
}
28+
n++;
29+
cout << "Array after insertion: ";
30+
for (int i = 0; i < n; i++) {
31+
cout << newArr[i] << " ";
32+
}
33+
cout << endl;
34+
35+
// Delete an element (inefficient)
36+
for (int i = 2; i < n - 1; i++) {
37+
newArr[i] = newArr[i + 1];
38+
}
39+
n--;
40+
cout << "Array after deletion: ";
41+
for (int i = 0; i < n; i++) {
42+
cout << newArr[i] << " ";
43+
}
44+
cout << endl;
45+
46+
// Traverse the array
47+
cout << "Traversing the array: ";
48+
for (int i = 0; i < n; i++) {
49+
cout << newArr[i] << " ";
50+
}
51+
cout << endl;
52+
53+
return 0;
54+
}
55+
```
56+
57+
In this example:
58+
- We declare and initialize an array.
59+
- We access an element using its index.
60+
- We insert a new element at a specific index, which requires shifting elements.
61+
- We delete an element, which also requires shifting elements.
62+
- We traverse the array and print each element.

src/data-structure/array/index.md

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# Array
2+
3+
### What is an Array?
4+
5+
An array is a data structure that consists of a collection of elements, each identified by at least one array index or key. Arrays are one of the simplest and most widely used data structures in programming. They store elements of the same type in contiguous memory locations, allowing efficient access to any element using its index.
6+
7+
### Key Characteristics
8+
9+
1. **Fixed Size**: The size of an array is determined at the time of its creation and cannot be changed dynamically.
10+
2. **Homogeneous Elements**: All elements in an array are of the same data type.
11+
3. **Contiguous Memory Allocation**: Elements are stored in consecutive memory locations, allowing for efficient index-based access.
12+
4. **Indexed Access**: Elements can be accessed directly using their index, typically starting from 0 in most programming languages.
13+
14+
### Types of Arrays
15+
16+
1. **One-Dimensional Array**: A linear array where elements are accessed using a single index.
17+
- Example: `int arr[5] = {1, 2, 3, 4, 5};`
18+
19+
2. **Multi-Dimensional Array**: Arrays with more than one dimension, such as two-dimensional arrays (matrices).
20+
- Example: `int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};`
21+
22+
3. **Dynamic Arrays**: Arrays that can change size dynamically during runtime, such as vectors in C++ or ArrayList in Java.
23+
24+
### Operations on Arrays
25+
26+
1. **Accessing Elements**
27+
- Elements are accessed using their index.
28+
- Example: `arr[2]` accesses the third element in the array `arr`.
29+
30+
2. **Insertion**
31+
- Adding an element at a specific index requires shifting elements to make space.
32+
- Example: To insert an element at index 2, shift elements from index 2 onwards and then place the new element.
33+
34+
3. **Deletion**
35+
- Removing an element requires shifting elements to fill the gap.
36+
- Example: To delete an element at index 2, shift elements from index 3 onwards one position to the left.
37+
38+
4. **Traversal**
39+
- Visiting each element of the array for processing.
40+
- Example: Using a loop to print all elements of the array.
41+
42+
5. **Searching**
43+
- Finding the index of an element in the array.
44+
- Linear Search: O(n) time complexity.
45+
- Binary Search: O(log n) time complexity (requires sorted array).
46+
47+
6. **Sorting**
48+
- Arranging elements in a specific order (ascending or descending).
49+
- Example: Using sorting algorithms like Quick Sort, Merge Sort, or Bubble Sort.
50+
51+
### Advantages of Arrays
52+
53+
1. **Constant-Time Access**: Elements can be accessed in O(1) time using their index.
54+
2. **Memory Efficiency**: Arrays have a low memory overhead compared to other data structures like linked lists.
55+
3. **Cache-Friendly**: Contiguous memory allocation makes arrays more cache-friendly, leading to better performance in terms of memory access speed.
56+
57+
### Disadvantages of Arrays
58+
59+
1. **Fixed Size**: The size of the array is fixed and cannot be changed after its creation, leading to potential wastage of memory or insufficient space.
60+
2. **Inefficient Insertion/Deletion**: Inserting or deleting elements, especially in the middle, can be inefficient as it requires shifting elements.
61+
3. **Homogeneous Data**: Arrays can only store elements of the same type, limiting flexibility.
62+
63+
### Applications of Arrays
64+
65+
1. **Storing and Accessing Data**: Arrays are used to store data that needs to be accessed quickly using indices.
66+
2. **Implementation of Other Data Structures**: Arrays are the foundation for implementing other data structures like stacks, queues, and hash tables.
67+
3. **Mathematical Computations**: Arrays are used in scientific computations and matrix operations.
68+
4. **Graphics and Image Processing**: Arrays are used to store pixel values and manipulate images.
Lines changed: 225 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,225 @@
1+
# Implementation
2+
3+
### Java Implementation of a Graph
4+
5+
Here’s a simple implementation of a graph in Java using an adjacency list representation.
6+
7+
#### Graph Class
8+
9+
```java
10+
import java.util.*;
11+
12+
class Graph {
13+
private int numVertices;
14+
private LinkedList<Integer>[] adjLists;
15+
16+
// Constructor
17+
public Graph(int vertices) {
18+
numVertices = vertices;
19+
adjLists = new LinkedList[vertices];
20+
for (int i = 0; i < vertices; i++) {
21+
adjLists[i] = new LinkedList<>();
22+
}
23+
}
24+
25+
// Add edge
26+
public void addEdge(int src, int dest) {
27+
adjLists[src].add(dest);
28+
adjLists[dest].add(src); // For undirected graph, add both connections
29+
}
30+
31+
// Print the graph
32+
public void printGraph() {
33+
for (int i = 0; i < numVertices; i++) {
34+
System.out.print("Vertex " + i + ":");
35+
for (Integer node : adjLists[i]) {
36+
System.out.print(" -> " + node);
37+
}
38+
System.out.println();
39+
}
40+
}
41+
42+
// Depth First Search (DFS) traversal
43+
public void DFS(int vertex) {
44+
boolean[] visited = new boolean[numVertices];
45+
DFSUtil(vertex, visited);
46+
}
47+
48+
private void DFSUtil(int vertex, boolean[] visited) {
49+
visited[vertex] = true;
50+
System.out.print(vertex + " ");
51+
52+
for (int adj : adjLists[vertex]) {
53+
if (!visited[adj]) {
54+
DFSUtil(adj, visited);
55+
}
56+
}
57+
}
58+
59+
// Breadth First Search (BFS) traversal
60+
public void BFS(int startVertex) {
61+
boolean[] visited = new boolean[numVertices];
62+
LinkedList<Integer> queue = new LinkedList<>();
63+
64+
visited[startVertex] = true;
65+
queue.add(startVertex);
66+
67+
while (queue.size() != 0) {
68+
int vertex = queue.poll();
69+
System.out.print(vertex + " ");
70+
71+
for (int adj : adjLists[vertex]) {
72+
if (!visited[adj]) {
73+
visited[adj] = true;
74+
queue.add(adj);
75+
}
76+
}
77+
}
78+
}
79+
80+
public static void main(String[] args) {
81+
Graph graph = new Graph(5);
82+
83+
graph.addEdge(0, 1);
84+
graph.addEdge(0, 4);
85+
graph.addEdge(1, 2);
86+
graph.addEdge(1, 3);
87+
graph.addEdge(1, 4);
88+
graph.addEdge(2, 3);
89+
graph.addEdge(3, 4);
90+
91+
graph.printGraph();
92+
93+
System.out.println("Depth First Search starting from vertex 0:");
94+
graph.DFS(0);
95+
96+
System.out.println("\nBreadth First Search starting from vertex 0:");
97+
graph.BFS(0);
98+
}
99+
}
100+
```
101+
102+
### Explanation
103+
104+
**Graph Class:**
105+
106+
```java
107+
class Graph {
108+
private int numVertices;
109+
private LinkedList<Integer>[] adjLists;
110+
111+
// Constructor
112+
public Graph(int vertices) {
113+
numVertices = vertices;
114+
adjLists = new LinkedList[vertices];
115+
for (int i = 0; i < vertices; i++) {
116+
adjLists[i] = new LinkedList<>();
117+
}
118+
}
119+
}
120+
```
121+
122+
The `Graph` class represents a graph with a specified number of vertices. The adjacency list is used to store the graph, with each vertex having a linked list of its adjacent vertices.
123+
124+
**Add Edge Function:**
125+
126+
```java
127+
public void addEdge(int src, int dest) {
128+
adjLists[src].add(dest);
129+
adjLists[dest].add(src); // For undirected graph, add both connections
130+
}
131+
```
132+
133+
This function adds an edge between two vertices in the graph. For an undirected graph, edges are added in both directions.
134+
135+
**Print Graph Function:**
136+
137+
```java
138+
public void printGraph() {
139+
for (int i = 0; i < numVertices; i++) {
140+
System.out.print("Vertex " + i + ":");
141+
for (Integer node : adjLists[i]) {
142+
System.out.print(" -> " + node);
143+
}
144+
System.out.println();
145+
}
146+
}
147+
```
148+
149+
This function prints the graph's adjacency list representation.
150+
151+
**Depth First Search (DFS) Function:**
152+
153+
```java
154+
public void DFS(int vertex) {
155+
boolean[] visited = new boolean[numVertices];
156+
DFSUtil(vertex, visited);
157+
}
158+
159+
private void DFSUtil(int vertex, boolean[] visited) {
160+
visited[vertex] = true;
161+
System.out.print(vertex + " ");
162+
163+
for (int adj : adjLists[vertex]) {
164+
if (!visited[adj]) {
165+
DFSUtil(adj, visited);
166+
}
167+
}
168+
}
169+
```
170+
171+
The DFS function recursively traverses the graph starting from a given vertex. It uses a boolean array to keep track of visited vertices.
172+
173+
**Breadth First Search (BFS) Function:**
174+
175+
```java
176+
public void BFS(int startVertex) {
177+
boolean[] visited = new boolean[numVertices];
178+
LinkedList<Integer> queue = new LinkedList<>();
179+
180+
visited[startVertex] = true;
181+
queue.add(startVertex);
182+
183+
while (queue.size() != 0) {
184+
int vertex = queue.poll();
185+
System.out.print(vertex + " ");
186+
187+
for (int adj : adjLists[vertex]) {
188+
if (!visited[adj]) {
189+
visited[adj] = true;
190+
queue.add(adj);
191+
}
192+
}
193+
}
194+
}
195+
```
196+
197+
The BFS function iteratively traverses the graph starting from a given vertex using a queue to manage the traversal.
198+
199+
**Main Method:**
200+
201+
```java
202+
public static void main(String[] args) {
203+
Graph graph = new Graph(5);
204+
205+
graph.addEdge(0, 1);
206+
graph.addEdge(0, 4);
207+
graph.addEdge(1, 2);
208+
graph.addEdge(1, 3);
209+
graph.addEdge(1, 4);
210+
graph.addEdge(2, 3);
211+
graph.addEdge(3, 4);
212+
213+
graph.printGraph();
214+
215+
System.out.println("Depth First Search starting from vertex 0:");
216+
graph.DFS(0);
217+
218+
System.out.println("\nBreadth First Search starting from vertex 0:");
219+
graph.BFS(0);
220+
}
221+
```
222+
223+
### Conclusion
224+
225+
This example demonstrates how to implement a graph in Java using an adjacency list. The `Graph` class includes methods to add edges, print the graph, and perform both Depth First Search (DFS) and Breadth First Search (BFS) traversals. This basic implementation can be extended to handle more complex operations and types of graphs, such as weighted and directed graphs.

src/data-structure/graph/index.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
### Understanding Graphs
2+
3+
A graph is a collection of nodes (also called vertices) and edges that connect pairs of nodes. Graphs can be:
4+
- **Directed or Undirected:** In a directed graph, edges have a direction, while in an undirected graph, edges do not.
5+
- **Weighted or Unweighted:** In a weighted graph, edges have weights or costs associated with them. In an unweighted graph, all edges are considered equal.
6+
- **Sparse or Dense:** A sparse graph has relatively few edges compared to the number of nodes, while a dense graph has many edges.
7+
8+
Graphs are used to represent various real-world systems such as social networks, transportation networks, and communication networks.

0 commit comments

Comments
 (0)