├── #include 2 | using namespace std; 3 | 4 | void conqurer(int *a, int s, int e, int mid) 5 | { 6 | int *merged = new int[e - s + 1]; 7 | int index1 = s; 8 | int index2 = mid + 1; 9 | int mainindex = 0; 10 | 11 | while (index1 <= mid && index2 <= e) 12 | { 13 | if (a[index1] <= a[index2]) 14 | { 15 | merged[mainindex++] = a[index1++]; 16 | } 17 | else 18 | { 19 | merged[mainindex++] = a[index2++]; 20 | } 21 | } 22 | while (index1 <= mid) 23 | { 24 | merged[mainindex++] = a[index1++]; 25 | } 26 | while (index2 <= e) 27 | { 28 | merged[mainindex++] = a[index2++]; 29 | } 30 | 31 | for (int i = 0, j = s; i < (e - s) + 1; i++, j++) 32 | { 33 | a[j] = merged[i]; 34 | } 35 | 36 | delete[] merged; 37 | } 38 | 39 | void divide(int *a, int s, int e) 40 | { 41 | while (s >= e) 42 | { 43 | return; 44 | } 45 | int mid = (s + e) / 2; 46 | divide(a, s, mid); 47 | divide(a, mid + 1, e); 48 | 49 | conqurer(a, s, e, mid); 50 | } 51 | int main() 52 | { 53 | int a[20] = {4, 5, 6, 3, 12}; 54 | int size = 5; 55 | divide(a, 0, size - 1); 56 | for (int i = 0; i < size; i++) 57 | { 58 | cout << a[i] << " "; 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhaysinghr516/Algorithms/9fea3eabb1596a91c3f8c058d9006f30d64840de/.DS_Store -------------------------------------------------------------------------------- /.github/workflows/greetings.yml: -------------------------------------------------------------------------------- 1 | name: Greetings 2 | 3 | on: [pull_request_target, issues] 4 | 5 | jobs: 6 | greeting: 7 | runs-on: ubuntu-latest 8 | permissions: 9 | issues: write 10 | pull-requests: write 11 | steps: 12 | - uses: actions/first-interaction@v1 13 | with: 14 | repo-token: ${{ secrets.GITHUB_TOKEN }} 15 | issue-message: "Message that will be displayed on users' first issue" 16 | pr-message: "Message that will be displayed on users' first pull request" 17 | -------------------------------------------------------------------------------- /.github/workflows/label.yml: -------------------------------------------------------------------------------- 1 | # This workflow will triage pull requests and apply a label based on the 2 | # paths that are modified in the pull request. 3 | # 4 | # To use this workflow, you will need to set up a .github/labeler.yml 5 | # file with configuration. For more information, see: 6 | # https://github.com/actions/labeler 7 | 8 | name: Labeler 9 | on: [pull_request_target] 10 | 11 | jobs: 12 | label: 13 | 14 | runs-on: ubuntu-latest 15 | permissions: 16 | contents: read 17 | pull-requests: write 18 | 19 | steps: 20 | - uses: actions/labeler@v4 21 | with: 22 | repo-token: "${{ secrets.GITHUB_TOKEN }}" 23 | -------------------------------------------------------------------------------- /.github/workflows/webpack.yml: -------------------------------------------------------------------------------- 1 | name: NodeJS with Webpack 2 | 3 | on: 4 | push: 5 | branches: [ "main" ] 6 | pull_request: 7 | branches: [ "main" ] 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | 13 | strategy: 14 | matrix: 15 | node-version: [14.x, 16.x, 18.x] 16 | 17 | steps: 18 | - uses: actions/checkout@v3 19 | 20 | - name: Use Node.js ${{ matrix.node-version }} 21 | uses: actions/setup-node@v3 22 | with: 23 | node-version: ${{ matrix.node-version }} 24 | 25 | - name: Build 26 | run: | 27 | npm install 28 | npx webpack 29 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/C++/Bellman-Ford-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | const int INF = numeric_limits::max(); 8 | 9 | void bellmanFord(const vector>& graph, int V, int E) { 10 | vector dist(V, INF); 11 | dist[0] = 0; 12 | 13 | for (int i = 0; i < V - 1; i++) { 14 | for (const auto& edge : graph) { 15 | int u = edge[0]; 16 | int v = edge[1]; 17 | int weight = edge[2]; 18 | if (dist[u] != INF && dist[u] + weight < dist[v]) { 19 | dist[v] = dist[u] + weight; 20 | } 21 | } 22 | } 23 | 24 | for (int i = 0; i < V; i++) { 25 | cout << "Distance from source to vertex " << i << ": " << dist[i] << endl; 26 | } 27 | } 28 | 29 | int main() { 30 | vector> graph = { 31 | {0, 1, -1}, 32 | {0, 2, 4}, 33 | {1, 2, 3}, 34 | {1, 3, 2}, 35 | {1, 4, 2}, 36 | {3, 2, 5}, 37 | {3, 1, 1}, 38 | {4, 3, -3} 39 | }; 40 | int V = 5, E = 8; 41 | 42 | bellmanFord(graph, V, E); 43 | 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/C/Bellman-Ford-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define V 5 6 | #define E 8 7 | 8 | void bellmanFord(int graph[][3]) { 9 | int dist[V]; 10 | for (int i = 0; i < V; i++) { 11 | dist[i] = INT_MAX; 12 | } 13 | dist[0] = 0; 14 | 15 | for (int i = 0; i < V - 1; i++) { 16 | for (int j = 0; j < E; j++) { 17 | int u = graph[j][0]; 18 | int v = graph[j][1]; 19 | int weight = graph[j][2]; 20 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 21 | dist[v] = dist[u] + weight; 22 | } 23 | } 24 | } 25 | 26 | for (int i = 0; i < V; i++) { 27 | printf("Distance from source to vertex %d: %d\n", i, dist[i]); 28 | } 29 | } 30 | 31 | int main() { 32 | int graph[E][3] = { 33 | {0, 1, -1}, 34 | {0, 2, 4}, 35 | {1, 2, 3}, 36 | {1, 3, 2}, 37 | {1, 4, 2}, 38 | {3, 2, 5}, 39 | {3, 1, 1}, 40 | {4, 3, -3} 41 | }; 42 | 43 | bellmanFord(graph); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/Go/Bellman-Ford-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | type Edge struct { 9 | src, dest, weight int 10 | } 11 | 12 | func BellmanFord(vertices int, edges []Edge, start int) ([]int, []int) { 13 | distances := make([]int, vertices) 14 | predecessors := make([]int, vertices) 15 | 16 | for i := 0; i < vertices; i++ { 17 | distances[i] = math.MaxInt32 18 | predecessors[i] = -1 19 | } 20 | distances[start] = 0 21 | 22 | for i := 1; i <= vertices-1; i++ { 23 | for _, edge := range edges { 24 | if distances[edge.src]+edge.weight < distances[edge.dest] { 25 | distances[edge.dest] = distances[edge.src] + edge.weight 26 | predecessors[edge.dest] = edge.src 27 | } 28 | } 29 | } 30 | 31 | for _, edge := range edges { 32 | if distances[edge.src]+edge.weight < distances[edge.dest] { 33 | fmt.Println("Negative weight cycle detected.") 34 | return nil, nil 35 | } 36 | } 37 | 38 | return distances, predecessors 39 | } 40 | 41 | func main() { 42 | vertices := 5 43 | edges := []Edge{ 44 | {0, 1, -1}, 45 | {0, 2, 4}, 46 | {1, 2, 3}, 47 | {1, 3, 2}, 48 | {1, 4, 2}, 49 | {3, 2, 5}, 50 | {3, 1, 1}, 51 | {4, 3, -3}, 52 | } 53 | 54 | start := 0 55 | distances, predecessors := BellmanFord(vertices, edges, start) 56 | 57 | if distances != nil && predecessors != nil { 58 | fmt.Println("Distances:", distances) 59 | fmt.Println("Predecessors:", predecessors) 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/Java/Bellman-Ford-Algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class BellmanFord { 4 | 5 | private static final int V = 5; 6 | private static final int E = 8; 7 | private static final int INF = Integer.MAX_VALUE; 8 | 9 | public static void bellmanFord(int[][] graph) { 10 | int[] dist = new int[V]; 11 | Arrays.fill(dist, INF); 12 | dist[0] = 0; 13 | 14 | for (int i = 0; i < V - 1; i++) { 15 | for (int[] edge : graph) { 16 | int u = edge[0]; 17 | int v = edge[1]; 18 | int weight = edge[2]; 19 | if (dist[u] != INF && dist[u] + weight < dist[v]) { 20 | dist[v] = dist[u] + weight; 21 | } 22 | } 23 | } 24 | 25 | for (int i = 0; i < V; i++) { 26 | System.out.println("Distance from source to vertex " + i + ": " + dist[i]); 27 | } 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[][] graph = { 32 | {0, 1, -1}, 33 | {0, 2, 4}, 34 | {1, 2, 3}, 35 | {1, 3, 2}, 36 | {1, 4, 2}, 37 | {3, 2, 5}, 38 | {3, 1, 1}, 39 | {4, 3, -3} 40 | }; 41 | 42 | bellmanFord(graph); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/JavaScript/Bellman-Ford-Algorithm.js: -------------------------------------------------------------------------------- 1 | const V = 5; 2 | const E = 8; 3 | const INF = Infinity; 4 | 5 | function bellmanFord(graph) { 6 | const dist = Array(V).fill(INF); 7 | dist[0] = 0; 8 | 9 | for (let i = 0; i < V - 1; i++) { 10 | for (const edge of graph) { 11 | const [u, v, weight] = edge; 12 | if (dist[u] !== INF && dist[u] + weight < dist[v]) { 13 | dist[v] = dist[u] + weight; 14 | } 15 | } 16 | } 17 | 18 | for (let i = 0; i < V; i++) { 19 | console.log(`Distance from source to vertex ${i}: ${dist[i]}`); 20 | } 21 | } 22 | 23 | const graph = [ 24 | [0, 1, -1], 25 | [0, 2, 4], 26 | [1, 2, 3], 27 | [1, 3, 2], 28 | [1, 4, 2], 29 | [3, 2, 5], 30 | [3, 1, 1], 31 | [4, 3, -3] 32 | ]; 33 | 34 | bellmanFord(graph); 35 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/Python/Bellman-Ford-Algorithm.py: -------------------------------------------------------------------------------- 1 | def bellman_ford(graph, source): 2 | num_vertices = len(graph) 3 | distances = [float('inf')] * num_vertices 4 | distances[source] = 0 5 | 6 | for _ in range(num_vertices - 1): 7 | for u, v, weight in graph: 8 | if distances[u] != float('inf') and distances[u] + weight < distances[v]: 9 | distances[v] = distances[u] + weight 10 | 11 | for u, v, weight in graph: 12 | if distances[u] != float('inf') and distances[u] + weight < distances[v]: 13 | print("Graph contains a negative-weight cycle") 14 | return 15 | 16 | print("Vertex\tDistance from Source") 17 | for i in range(num_vertices): 18 | print(f"{i}\t{distances[i]}") 19 | 20 | graph = [ 21 | (0, 1, -1), 22 | (0, 2, 4), 23 | (1, 2, 3), 24 | (1, 3, 2), 25 | (1, 4, 2), 26 | (3, 2, 5), 27 | (3, 1, 1), 28 | (4, 3, -3) 29 | ] 30 | 31 | bellman_ford(graph, 0) 32 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Bellman-Ford Algorithm 2 | 3 | The Bellman-Ford algorithm is a graph search algorithm that finds the shortest path from a source vertex to all other vertices in a weighted, directed graph. It can handle negative weight edges, but not negative weight cycles. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V _ E) 8 | Average: O(V _ E) 9 | Worst: O(V \* E) 10 | 11 | ## Space Complexity 12 | 13 | O(V) 14 | 15 | ## Example Use Case 16 | 17 | Finding the shortest path from a source vertex to all other vertices in a graph with potential negative weight edges, such as currency exchange rates or transportation costs. 18 | -------------------------------------------------------------------------------- /Bellman Form Algorithm/Rust/Bellman-ford.rs: -------------------------------------------------------------------------------- 1 | /* The Bellman-Ford algorithm is used to find the shortest path from a source vertex to all other vertices in a weighted, directed graph. It can handle graphs with negative-weight edges, but it is not suitable for graphs with negative-weight cycles */ 2 | 3 | // Define a structure to represent an edge in the graph 4 | struct Edge { 5 | source: usize, // Source vertex of the edge 6 | destination: usize, // Destination vertex of the edge 7 | weight: i32, // Weight of the edge 8 | } 9 | 10 | // Define a structure to represent the graph 11 | struct Graph { 12 | vertices: usize, // Number of vertices in the graph 13 | edges: Vec, // List of edges in the graph 14 | } 15 | 16 | impl Graph { 17 | // Constructor for the Graph structure 18 | fn new(vertices: usize) -> Graph { 19 | Graph { 20 | vertices, 21 | edges: vec![], 22 | } 23 | } 24 | 25 | // Function to add an edge to the graph 26 | fn add_edge(&mut self, source: usize, destination: usize, weight: i32) { 27 | self.edges.push(Edge { 28 | source, 29 | destination, 30 | weight, 31 | }); 32 | } 33 | 34 | // Function to perform the Bellman-Ford algorithm 35 | fn bellman_ford(&self, source: usize) -> Vec { 36 | // Initialize the distance array with a large value for all vertices 37 | let mut distances = vec![i32::MAX; self.vertices]; 38 | distances[source] = 0; // Distance from the source to itself is 0 39 | 40 | // Relax all edges repeatedly to find the shortest paths 41 | for _ in 0..self.vertices - 1 { 42 | for edge in &self.edges { 43 | let u = edge.source; 44 | let v = edge.destination; 45 | let w = edge.weight; 46 | 47 | // Relax the edge if a shorter path is found 48 | if distances[u] != i32::MAX && distances[u] + w < distances[v] { 49 | distances[v] = distances[u] + w; 50 | } 51 | } 52 | } 53 | 54 | // Check for negative-weight cycles 55 | for edge in &self.edges { 56 | let u = edge.source; 57 | let v = edge.destination; 58 | let w = edge.weight; 59 | 60 | if distances[u] != i32::MAX && distances[u] + w < distances[v] { 61 | panic!("Graph contains a negative-weight cycle"); 62 | } 63 | } 64 | 65 | distances // Return the array of shortest distances 66 | } 67 | } 68 | 69 | fn main() { 70 | let vertices = 5; 71 | let mut graph = Graph::new(vertices); 72 | 73 | graph.add_edge(0, 1, -1); 74 | graph.add_edge(0, 2, 4); 75 | graph.add_edge(1, 2, 3); 76 | graph.add_edge(1, 3, 2); 77 | graph.add_edge(1, 4, 2); 78 | graph.add_edge(3, 2, 5); 79 | graph.add_edge(3, 1, 1); 80 | graph.add_edge(4, 3, -3); 81 | 82 | let source = 0; 83 | let distances = graph.bellman_ford(source); 84 | 85 | for (i, distance) in distances.iter().enumerate() { 86 | println!("Shortest distance from {} to {} is {}", source, i, distance); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /Binary Search Algorithm/C++/Binary-Search-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int binarySearch(const std::vector& arr, int x) { 5 | int left = 0; 6 | int right = arr.size() - 1; 7 | 8 | while (left <= right) { 9 | int mid = left + (right - left) / 2; 10 | 11 | if (arr[mid] == x) { 12 | return mid; 13 | } else if (arr[mid] < x) { 14 | left = mid + 1; 15 | } else { 16 | right = mid - 1; 17 | } 18 | } 19 | 20 | return -1; 21 | } 22 | 23 | int main() { 24 | std::vector arr = {2, 3, 4, 10, 40}; 25 | int x = 10; 26 | 27 | int result = binarySearch(arr, x); 28 | if (result != -1) { 29 | std::cout << "Element found at index " << result << std::endl; 30 | } else { 31 | std::cout << "Element not found in the array" << std::endl; 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Binary Search Algorithm/C/Binary-Search-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int binarySearch(int arr[], int n, int x) { 4 | int left = 0; 5 | int right = n - 1; 6 | 7 | while (left <= right) { 8 | int mid = left + (right - left) / 2; 9 | 10 | if (arr[mid] == x) { 11 | return mid; 12 | } else if (arr[mid] < x) { 13 | left = mid + 1; 14 | } else { 15 | right = mid - 1; 16 | } 17 | } 18 | 19 | return -1; 20 | } 21 | 22 | int main() { 23 | int arr[] = {2, 3, 4, 10, 40}; 24 | int n = sizeof(arr) / sizeof(arr[0]); 25 | int x = 10; 26 | 27 | int result = binarySearch(arr, n, x); 28 | if (result != -1) { 29 | printf("Element found at index %d\n", result); 30 | } else { 31 | printf("Element not found in the array\n"); 32 | } 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Binary Search Algorithm/Go/Binary-Search-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func binarySearch(arr []int, x int) int { 6 | left := 0 7 | right := len(arr) - 1 8 | 9 | for left <= right { 10 | mid := left + (right - left) / 2 11 | 12 | if arr[mid] == x { 13 | return mid 14 | } else if arr[mid] < x { 15 | left = mid + 1 16 | } else { 17 | right = mid - 1 18 | } 19 | } 20 | 21 | return -1 22 | } 23 | 24 | func main() { 25 | arr := []int{2, 3, 4, 10, 40} 26 | x := 10 27 | 28 | result := binarySearch(arr, x) 29 | if result != -1 { 30 | fmt.Println("Element found at index", result) 31 | } else { 32 | fmt.Println("Element not found in the array") 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Binary Search Algorithm/Java/Binary-Search-Algorithm.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | public static int binarySearch(int[] array, int target) { 3 | int left = 0; 4 | int right = array.length - 1; 5 | 6 | while (left <= right) { 7 | int middle = left + (right - left) / 2; 8 | 9 | if (array[middle] == target) { 10 | return middle; 11 | } else if (array[middle] < target) { 12 | left = middle + 1; 13 | } else { 14 | right = middle - 1; 15 | } 16 | } 17 | 18 | return -1; 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] array = {2, 3, 4, 10, 40}; 23 | int target = 10; 24 | 25 | int result = binarySearch(array, target); 26 | if (result == -1) { 27 | System.out.println("Element not found"); 28 | } else { 29 | System.out.println("Element found at index: " + result); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Binary Search Algorithm/JavaScript/Binary-Search-Algorithm.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, x) { 2 | let left = 0; 3 | let right = arr.length - 1; 4 | 5 | while (left <= right) { 6 | const mid = left + Math.floor((right - left) / 2); 7 | 8 | if (arr[mid] === x) { 9 | return mid; 10 | } else if (arr[mid] < x) { 11 | left = mid + 1; 12 | } else { 13 | right = mid - 1; 14 | } 15 | } 16 | 17 | return -1; 18 | } 19 | 20 | const arr = [2, 3, 4, 10, 40]; 21 | const x = 10; 22 | 23 | const result = binarySearch(arr, x); 24 | if (result !== -1) { 25 | console.log(`Element found at index ${result}`); 26 | } else { 27 | console.log("Element not found in the array"); 28 | } 29 | -------------------------------------------------------------------------------- /Binary Search Algorithm/Python/Binary-Search-Algorithm.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, x): 2 | left = 0 3 | right = len(arr) - 1 4 | 5 | while left <= right: 6 | mid = left + (right - left) // 2 7 | 8 | if arr[mid] == x: 9 | return mid 10 | elif arr[mid] < x: 11 | left = mid + 1 12 | else: 13 | right = mid - 1 14 | 15 | return -1 16 | 17 | arr = [2, 3, 4, 10, 40] 18 | x = 10 19 | 20 | result = binary_search(arr, x) 21 | if result != -1: 22 | print(f"Element found at index {result}") 23 | else: 24 | print("Element not found in the array") 25 | -------------------------------------------------------------------------------- /Binary Search Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Algorithm 2 | 3 | Binary search is an efficient search algorithm that works on a sorted array or list. It repeatedly divides the search interval in half, narrowing down the possible locations of the target value until it is found or the interval is empty. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(1) 8 | Average: O(log n) 9 | Worst: O(log n) 10 | 11 | ## Space Complexity 12 | 13 | O(1) for iterative implementation 14 | O(log n) for recursive implementation 15 | 16 | ## Example Use Case 17 | 18 | Searching for a specific value in a large, sorted dataset, such as looking up a word in a dictionary or finding a customer record in a database. 19 | -------------------------------------------------------------------------------- /Binary Search Algorithm/Rust/Binary_Search_Algorithm.rs: -------------------------------------------------------------------------------- 1 | fn binary_search(arr: &[i32], x: i32) -> i32 { 2 | let mut left = 0; 3 | let mut right = arr.len() as i32 - 1; 4 | 5 | while left <= right { 6 | let mid = left + (right - left) / 2; 7 | 8 | if arr[mid as usize] == x { 9 | return mid; 10 | } else if arr[mid as usize] < x { 11 | left = mid + 1; 12 | } else { 13 | right = mid - 1; 14 | } 15 | } 16 | 17 | -1 18 | } 19 | 20 | fn main() { 21 | let arr = vec![2, 3, 4, 10, 40]; 22 | let x = 10; 23 | 24 | let result = binary_search(&arr, x); 25 | if result != -1 { 26 | println!("Element found at index {}", result); 27 | } else { 28 | println!("Element not found in the array"); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Binary Search Algorithm/Rust/Binary_search.rs: -------------------------------------------------------------------------------- 1 | /*Binary search is an efficient algorithm for finding an item from a sorted list of items. 2 | It works by repeatedly dividing in half the portion of the list that could contain the item, 3 | until you've narrowed down the possible locations to just one 4 | 5 | Binary search runs in logarithmic time in the worst case, making 6 | O(log n) comparisons, where n is the number of elements in the array. 7 | Binary search is faster than linear search except for small arrays. 8 | However, the array must be sorted first to be able to apply binary search. 9 | */ 10 | 11 | 12 | fn binary_search(arr: &[i32], target: i32) -> Option { 13 | let mut low = 0; // Initialize the low index to the beginning of the array 14 | let mut high = arr.len() - 1; // Initialize the high index to the end of the array 15 | 16 | while low <= high { 17 | let mid = low + (high - low) / 2; // Calculate the middle index 18 | 19 | if arr[mid] == target { 20 | return Some(mid); // Target found, return the index 21 | } else if arr[mid] < target { 22 | low = mid + 1; // Adjust the low index to search the right half 23 | } else { 24 | high = mid - 1; // Adjust the high index to search the left half 25 | } 26 | } 27 | 28 | None // Target not found in the array 29 | } 30 | 31 | fn main() { 32 | let arr = [1, 3, 5, 7, 9, 11, 13, 15]; 33 | let target = 7; 34 | 35 | if let Some(index) = binary_search(&arr, target) { 36 | println!("Target {} found at index {}.", target, index); 37 | } else { 38 | println!("Target {} not found in the array.", target); 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/C++/Boyer-Moore-Majority-Vote-Algortihm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int find_majority_element(const std::vector& arr) { 5 | int candidate = 0; 6 | int count = 0; 7 | 8 | for (int num : arr) { 9 | if (count == 0) { 10 | candidate = num; 11 | } 12 | count += (num == candidate) ? 1 : -1; 13 | } 14 | 15 | return candidate; 16 | } 17 | 18 | int main() { 19 | std::vector arr = {2, 2, 1, 1, 2, 2}; 20 | 21 | int result = find_majority_element(arr); 22 | std::cout << "Majority element is: " << result << std::endl; 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/C/Boyer-Moore-Majority-Vote-Algortihm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int find_majority_element(int arr[], int n) { 4 | int candidate = 0; 5 | int count = 0; 6 | 7 | for (int i = 0; i < n; i++) { 8 | if (count == 0) { 9 | candidate = arr[i]; 10 | } 11 | count += (arr[i] == candidate) ? 1 : -1; 12 | } 13 | 14 | return candidate; 15 | } 16 | 17 | int main() { 18 | int arr[] = {2, 2, 1, 1, 2, 2}; 19 | int n = sizeof(arr) / sizeof(arr[0]); 20 | 21 | int result = find_majority_element(arr, n); 22 | printf("Majority element is: %d\n", result); 23 | 24 | return 0; 25 | } 26 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/Go/Boyer-Moore-Majority-Vote-Algortihm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func find_majority_element(arr []int) int { 6 | candidate := 0 7 | count := 0 8 | 9 | for _, num := range arr { 10 | if count == 0 { 11 | candidate = num 12 | } 13 | if num == candidate { 14 | count++ 15 | } else { 16 | count-- 17 | } 18 | } 19 | 20 | return candidate 21 | } 22 | 23 | func main() { 24 | arr := []int{2, 2, 1, 1, 2, 2} 25 | 26 | result := find_majority_element(arr) 27 | fmt.Println("Majority element is:", result) 28 | } 29 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/Java/Boyer-Moore-Majority-Vote-Algortihm.java: -------------------------------------------------------------------------------- 1 | public class MajorityElement { 2 | 3 | public static int findMajorityElement(int[] arr) { 4 | int candidate = 0; 5 | int count = 0; 6 | 7 | for (int num : arr) { 8 | if (count == 0) { 9 | candidate = num; 10 | } 11 | count += (num == candidate) ? 1 : -1; 12 | } 13 | 14 | return candidate; 15 | } 16 | 17 | public static void main(String[] args) { 18 | int[] arr = {2, 2, 1, 1, 2, 2}; 19 | 20 | int result = findMajorityElement(arr); 21 | System.out.println("Majority element is: " + result); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/JavaScript/Boyer-Moore-Majority-Vote-Algortihm.js: -------------------------------------------------------------------------------- 1 | function findMajorityElement(arr) { 2 | let candidate = 0; 3 | let count = 0; 4 | 5 | for (const num of arr) { 6 | if (count === 0) { 7 | candidate = num; 8 | } 9 | count += (num === candidate) ? 1 : -1; 10 | } 11 | 12 | return candidate; 13 | } 14 | 15 | const arr = [2, 2, 1, 1, 2, 2]; 16 | 17 | const result = findMajorityElement(arr); 18 | console.log("Majority element is:", result); 19 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/Python/Boyer-Moore-Majority-Vote-Algortihm.py: -------------------------------------------------------------------------------- 1 | def find_majority_element(arr): 2 | candidate = 0 3 | count = 0 4 | 5 | for num in arr: 6 | if count == 0: 7 | candidate = num 8 | count += 1 if num == candidate else -1 9 | 10 | return candidate 11 | 12 | arr = [2, 2, 1, 1, 2, 2] 13 | 14 | result = find_majority_element(arr) 15 | print("Majority element is:", result) 16 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Boyer-Moore Majority Vote Algorithm 2 | 3 | The Boyer-Moore Majority Vote algorithm is an efficient algorithm used to find the majority element in an array (an element that appears more than n/2 times), if it exists. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n) 8 | Average: O(n) 9 | Worst: O(n) 10 | 11 | ## Space Complexity 12 | 13 | O(1) 14 | 15 | ## Example Use Case 16 | 17 | Determining the most common element in a list, such as finding the most frequently occurring color in a list of colors or the most frequent product purchased in a list of transactions. 18 | -------------------------------------------------------------------------------- /Boyer-Moore Majority Vote Algortihm/Rust/Boyer-Moore-Majority-Vote-Algorithm.rs: -------------------------------------------------------------------------------- 1 | fn boyer_moore_majority_vote(nums: &[i32]) -> Option { 2 | let mut candidate = 0; 3 | let mut count = 0; 4 | 5 | for &num in nums { 6 | if count == 0 { 7 | candidate = num; 8 | count = 1; 9 | } else if candidate == num { 10 | count += 1; 11 | } else { 12 | count -= 1; 13 | } 14 | } 15 | 16 | // After the first pass, 'candidate' may be the majority element, but we need to verify it. 17 | count = 0; 18 | for &num in nums { 19 | if candidate == num { 20 | count += 1; 21 | } 22 | } 23 | 24 | if count > nums.len() / 2 { 25 | Some(candidate) 26 | } else { 27 | None 28 | } 29 | } 30 | 31 | fn main() { 32 | let nums = vec![3, 3, 4, 2, 4, 4, 2, 4, 4]; 33 | if let Some(majority_element) = boyer_moore_majority_vote(&nums) { 34 | println!("The majority element is: {}", majority_element); 35 | } else { 36 | println!("No majority element found."); 37 | } 38 | } -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/C++/Breadth-First-Search-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class Graph { 7 | public: 8 | Graph(int vertices) : vertices(vertices) { 9 | adj_list.resize(vertices); 10 | } 11 | 12 | void add_edge(int src, int dest) { 13 | adj_list[src].push_back(dest); 14 | adj_list[dest].push_back(src); 15 | } 16 | 17 | void bfs(int start_vertex) { 18 | std::vector visited(vertices, false); 19 | std::queue q; 20 | 21 | visited[start_vertex] = true; 22 | q.push(start_vertex); 23 | 24 | while (!q.empty()) { 25 | int current_vertex = q.front(); 26 | q.pop(); 27 | 28 | std::cout << "Visited " << current_vertex << std::endl; 29 | 30 | for (int adj_vertex : adj_list[current_vertex]) { 31 | if (!visited[adj_vertex]) { 32 | visited[adj_vertex] = true; 33 | q.push(adj_vertex); 34 | } 35 | } 36 | } 37 | } 38 | 39 | private: 40 | int vertices; 41 | std::vector> adj_list; 42 | }; 43 | 44 | int main() { 45 | Graph g(6); 46 | 47 | g.add_edge(0, 1); 48 | g.add_edge(0, 2); 49 | g.add_edge(1, 3); 50 | g.add_edge(1, 4); 51 | g.add_edge(2, 4); 52 | g.add_edge(3, 5); 53 | g.add_edge(4, 5); 54 | 55 | g.bfs(0); 56 | 57 | return 0; 58 | } 59 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/C/Breadth-First-Search-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct node { 5 | int vertex; 6 | struct node* next; 7 | } node; 8 | 9 | typedef struct graph { 10 | int num_vertices; 11 | int* visited; 12 | node** adj_list; 13 | } graph; 14 | 15 | node* create_node(int vertex); 16 | graph* create_graph(int vertices); 17 | void add_edge(graph* g, int src, int dest); 18 | void bfs(graph* g, int start_vertex); 19 | 20 | int main() { 21 | graph* g = create_graph(6); 22 | 23 | add_edge(g, 0, 1); 24 | add_edge(g, 0, 2); 25 | add_edge(g, 1, 3); 26 | add_edge(g, 1, 4); 27 | add_edge(g, 2, 4); 28 | add_edge(g, 3, 5); 29 | add_edge(g, 4, 5); 30 | 31 | bfs(g, 0); 32 | 33 | return 0; 34 | } 35 | 36 | node* create_node(int vertex) { 37 | node* new_node = (node*)malloc(sizeof(node)); 38 | new_node->vertex = vertex; 39 | new_node->next = NULL; 40 | return new_node; 41 | } 42 | 43 | graph* create_graph(int vertices) { 44 | graph* g = (graph*)malloc(sizeof(graph)); 45 | g->num_vertices = vertices; 46 | g->adj_list = (node**)malloc(vertices * sizeof(node*)); 47 | g->visited = (int*)malloc(vertices * sizeof(int)); 48 | 49 | for (int i = 0; i < vertices; i++) { 50 | g->adj_list[i] = NULL; 51 | g->visited[i] = 0; 52 | } 53 | 54 | return g; 55 | } 56 | 57 | void add_edge(graph* g, int src, int dest) { 58 | node* new_node = create_node(dest); 59 | new_node->next = g->adj_list[src]; 60 | g->adj_list[src] = new_node; 61 | 62 | new_node = create_node(src); 63 | new_node->next = g->adj_list[dest]; 64 | g->adj_list[dest] = new_node; 65 | } 66 | 67 | void bfs(graph* g, int start_vertex) { 68 | node** queue = (node**)malloc(g->num_vertices * sizeof(node*)); 69 | int front = 0; 70 | int back = 0; 71 | 72 | g->visited[start_vertex] = 1; 73 | queue[back++] = g->adj_list[start_vertex]; 74 | 75 | while (front != back) { 76 | node* current_vertex = queue[front++]; 77 | printf("Visited %d\n", current_vertex->vertex); 78 | 79 | node* temp = g->adj_list[current_vertex->vertex]; 80 | while (temp) { 81 | int adj_vertex = temp->vertex; 82 | if (!g->visited[adj_vertex]) { 83 | g->visited[adj_vertex] = 1; 84 | queue[back++] = g->adj_list[adj_vertex]; 85 | } 86 | temp = temp->next; 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/Go/Breadth-First-Search-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "container/list" 6 | ) 7 | 8 | type Graph struct { 9 | vertices int 10 | adj_list []list.List 11 | } 12 | 13 | func NewGraph(vertices int) *Graph { 14 | g := &Graph{ 15 | vertices: vertices, 16 | adj_list: make([]list.List, vertices), 17 | } 18 | return g 19 | } 20 | 21 | func (g *Graph) AddEdge(src, dest int) { 22 | g.adj_list[src].PushBack(dest) 23 | g.adj_list[dest].PushBack(src) 24 | } 25 | 26 | func (g *Graph) BFS(start_vertex int) { 27 | visited := make([]bool, g.vertices) 28 | queue := list.New() 29 | 30 | visited[start_vertex] = true 31 | queue.PushBack(start_vertex) 32 | 33 | for queue.Len() > 0 { 34 | current_vertex := queue.Front() 35 | queue.Remove(current_vertex) 36 | fmt.Printf("Visited %d\n", current_vertex.Value) 37 | 38 | for e := g.adj_list[current_vertex.Value.(int)].Front(); e != nil; e = e.Next() { 39 | adj_vertex := e.Value.(int) 40 | if !visited[adj_vertex] { 41 | visited[adj_vertex] = true 42 | queue.PushBack(adj_vertex) 43 | } 44 | } 45 | } 46 | } 47 | 48 | func main() { 49 | g := NewGraph(6) 50 | 51 | g.AddEdge(0, 1) 52 | g.AddEdge(0, 2) 53 | g.AddEdge(1, 3) 54 | g.AddEdge(1, 4) 55 | g.AddEdge(2, 4) 56 | g.AddEdge(3, 5) 57 | g.AddEdge(4, 5) 58 | 59 | g.BFS(0) 60 | } 61 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/Java/Breadth-First-Search-Algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class BFS { 4 | static class Graph { 5 | int vertices; 6 | LinkedList[] adj_list; 7 | 8 | Graph(int vertices) { 9 | this.vertices = vertices; 10 | adj_list = new LinkedList[vertices]; 11 | 12 | for (int i = 0; i < vertices; i++) { 13 | adj_list[i] = new LinkedList<>(); 14 | } 15 | } 16 | 17 | void addEdge(int src, int dest) { 18 | adj_list[src].add(dest); 19 | adj_list[dest].add(src); 20 | } 21 | 22 | void bfs(int start_vertex) { 23 | boolean[] visited = new boolean[vertices]; 24 | Queue queue = new LinkedList<>(); 25 | 26 | visited[start_vertex] = true; 27 | queue.add(start_vertex); 28 | 29 | while (!queue.isEmpty()) { 30 | int current_vertex = queue.poll(); 31 | System.out.println("Visited " + current_vertex); 32 | 33 | for (int adj_vertex : adj_list[current_vertex]) { 34 | if (!visited[adj_vertex]) { 35 | visited[adj_vertex] = true; 36 | queue.add(adj_vertex); 37 | } 38 | } 39 | } 40 | } 41 | } 42 | 43 | public static void main(String[] args) { 44 | Graph g = new Graph(6); 45 | 46 | g.addEdge(0, 1); 47 | g.addEdge(0, 2); 48 | g.addEdge(1, 3); 49 | g.addEdge(1, 4); 50 | g.addEdge(2, 4); 51 | g.addEdge(3, 5); 52 | g.addEdge(4, 5); 53 | 54 | g.bfs(0); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/JavaScript/Breadth-First-Search-Algorithm.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor(vertices) { 3 | this.vertices = vertices; 4 | this.adj_list = new Array(vertices).fill(null).map(() => []); 5 | } 6 | 7 | addEdge(src, dest) { 8 | this.adj_list[src].push(dest); 9 | this.adj_list[dest].push(src); 10 | } 11 | 12 | bfs(start_vertex) { 13 | const visited = new Array(this.vertices).fill(false); 14 | const queue = [start_vertex]; 15 | 16 | visited[start_vertex] = true; 17 | 18 | while (queue.length > 0) { 19 | const current_vertex = queue.shift(); 20 | console.log("Visited", current_vertex); 21 | 22 | for (const adj_vertex of this.adj_list[current_vertex]) { 23 | if (!visited[adj_vertex]) { 24 | visited[adj_vertex] = true; 25 | queue.push(adj_vertex); 26 | } 27 | } 28 | } 29 | } 30 | } 31 | 32 | const g = new Graph(6); 33 | 34 | g.addEdge(0, 1); 35 | g.addEdge(0, 2); 36 | g.addEdge(1, 3); 37 | g.addEdge(1, 4); 38 | g.addEdge(2, 4); 39 | g.addEdge(3, 5); 40 | g.addEdge(4, 5); 41 | 42 | g.bfs(0); 43 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/Python/Breadth-First-Search-Algorithm.py: -------------------------------------------------------------------------------- 1 | from collections import deque 2 | 3 | class Graph: 4 | def __init__(self, vertices): 5 | self.vertices = vertices 6 | self.adj_list = [[] for _ in range(vertices)] 7 | 8 | def add_edge(self, src, dest): 9 | self.adj_list[src].append(dest) 10 | self.adj_list[dest].append(src) 11 | 12 | def bfs(self, start_vertex): 13 | visited = [False] * self.vertices 14 | queue = deque([start_vertex]) 15 | 16 | visited[start_vertex] = True 17 | 18 | while queue: 19 | current_vertex = queue.popleft() 20 | print("Visited", current_vertex) 21 | 22 | for adj_vertex in self.adj_list[current_vertex]: 23 | if not visited[adj_vertex]: 24 | visited[adj_vertex] = True 25 | queue.append(adj_vertex) 26 | 27 | g = Graph(6) 28 | 29 | g.add_edge(0, 1) 30 | g.add_edge(0, 2) 31 | g.add_edge(1, 3) 32 | g.add_edge(1, 4) 33 | g.add_edge(2, 4) 34 | g.add_edge(3, 5) 35 | g.add_edge(4, 5) 36 | 37 | g.bfs(0) 38 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Breadth-First Search (BFS) Algorithm 2 | 3 | Breadth-First Search (BFS) is a graph traversal algorithm that visits all the vertices of a graph in breadthward motion. It explores all neighboring vertices at the current level before moving on to the vertices at the next level. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V + E) 8 | Average: O(V + E) 9 | Worst: O(V + E) 10 | 11 | ## Space Complexity 12 | 13 | O(V) 14 | 15 | ## Example Use Case 16 | 17 | Finding the shortest path between two vertices in an unweighted graph, such as determining the minimum number of steps to reach a destination in a maze or the degrees of separation between two people in a social network. 18 | -------------------------------------------------------------------------------- /Breadth First Search(BFS) Algorithm/Rust/Breadth_First_Search_Algorithm.rs: -------------------------------------------------------------------------------- 1 | use std::collections::{LinkedList, VecDeque}; 2 | 3 | struct Graph { 4 | vertices: usize, 5 | adj_list: Vec>, 6 | } 7 | 8 | impl Graph { 9 | fn new(vertices: usize) -> Graph { 10 | let mut adj_list = vec![LinkedList::new(); vertices]; 11 | Graph { vertices, adj_list } 12 | } 13 | 14 | fn add_edge(&mut self, src: usize, dest: usize) { 15 | self.adj_list[src].push_back(dest); 16 | self.adj_list[dest].push_back(src); 17 | } 18 | 19 | fn bfs(&self, start_vertex: usize) { 20 | let mut visited = vec![false; self.vertices]; 21 | let mut queue = VecDeque::new(); 22 | 23 | visited[start_vertex] = true; 24 | queue.push_back(start_vertex); 25 | 26 | while let Some(current_vertex) = queue.pop_front() { 27 | println!("Visited {}", current_vertex); 28 | 29 | for &adj_vertex in &self.adj_list[current_vertex] { 30 | if !visited[adj_vertex] { 31 | visited[adj_vertex] = true; 32 | queue.push_back(adj_vertex); 33 | } 34 | } 35 | } 36 | } 37 | } 38 | 39 | fn main() { 40 | let mut g = Graph::new(6); 41 | 42 | g.add_edge(0, 1); 43 | g.add_edge(0, 2); 44 | g.add_edge(1, 3); 45 | g.add_edge(1, 4); 46 | g.add_edge(2, 4); 47 | g.add_edge(3, 5); 48 | g.add_edge(4, 5); 49 | 50 | g.bfs(0); 51 | } 52 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/C++/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void bubbleSort(std :: vector& arr) { 5 | int n = arr.size(); 6 | for (int i = 0; i < n; i++) { 7 | for (int j = 0; j < n - i - 1; j++) { 8 | if (arr[j] > arr[j + 1]) { 9 | std :: swap(arr[j], arr[j+1]); 10 | } 11 | } 12 | } 13 | } 14 | 15 | int main() { 16 | std :: vector arr = {12, 92, 65, 4, 27, 19, 88}; 17 | 18 | bubbleSort(arr); 19 | 20 | printf("Sorted array: "); 21 | for (int i = 0; i < arr.size(); i++) { 22 | std :: cout < 2 | 3 | void bubbleSort(int arr[], int n) { 4 | for (int i = 0; i < n - 1; i++) { 5 | for (int j = 0; j < n - i - 1; j++) { 6 | if (arr[j] > arr[j + 1]) { 7 | int temp = arr[j]; 8 | arr[j] = arr[j + 1]; 9 | arr[j + 1] = temp; 10 | } 11 | } 12 | } 13 | } 14 | 15 | int main() { 16 | int arr[] = {12, 92, 65, 4, 27, 19, 88}; 17 | int n = sizeof(arr) / sizeof(arr[0]); 18 | 19 | bubbleSort(arr, n); 20 | 21 | printf("Sorted array: "); 22 | for (int i = 0; i < n; i++) { 23 | printf("%d ", arr[i]); 24 | } 25 | printf("\n"); 26 | 27 | return 0; 28 | } 29 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/Go/BubbleSort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | /* 8 | Bubble Sort Implimentation in Go 9 | 10 | Time Complexity O(n^2) 11 | */ 12 | func main() { 13 | var arr = []int{24, 9, 15, 1, 4, 8, 6} 14 | fmt.Println("Before sort: ", arr) 15 | bubbleSort(arr) 16 | fmt.Println("After sort: ", arr) 17 | } 18 | 19 | func bubbleSort(arr []int) { 20 | for i := 0; i < len(arr); i++ { 21 | for j := 1; j < len(arr)-i; j++ { 22 | if arr[j-1] > arr[j] { 23 | swap(arr, j-1, j) 24 | } 25 | } 26 | } 27 | } 28 | 29 | func swap(arr []int, i, j int) { 30 | var temp = arr[i] 31 | arr[i] = arr[j] 32 | arr[j] = temp 33 | 34 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/Java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | package BubbleSortAlgorithm; 2 | 3 | import java.util.Arrays; 4 | 5 | public class BubbleSort { 6 | 7 | public static void main(String[] args) { 8 | int[] arr = {18, 12, 19, 18, 29, 89, 98}; 9 | bubbleSort(arr); 10 | System.out.println("After Sorting the Integer Array: " + Arrays.toString(arr)); 11 | } 12 | 13 | public static void bubbleSort(int[] arr) { 14 | boolean swap; 15 | for (int i = 0; i < arr.length - 1; i++) { 16 | swap = false; 17 | for (int j = 0; j < arr.length - 1 - i; j++) { 18 | if (arr[j] > arr[j + 1]) { 19 | int temp = arr[j]; 20 | arr[j] = arr[j + 1]; 21 | arr[j + 1] = temp; 22 | swap = true; 23 | } 24 | } 25 | if (!swap) { 26 | break; 27 | } 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/Javascript/BubbleSort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(arr) { 2 | const n = arr.length; 3 | let swapped; 4 | 5 | do { 6 | swapped = false; 7 | 8 | for (let i = 0; i < n - 1; i++) { 9 | if (arr[i] > arr[i + 1]) { 10 | // Swap the elements 11 | const temp = arr[i]; 12 | arr[i] = arr[i + 1]; 13 | arr[i + 1] = temp; 14 | 15 | swapped = true; 16 | } 17 | } 18 | } while (swapped); 19 | 20 | return arr; 21 | } 22 | 23 | const unsortedArray = [97, 45, 5, 37, 10, 75, 19, 57, 85, 65, 24]; 24 | const sortedArray = bubbleSort(unsortedArray); 25 | console.log(sortedArray); 26 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/Python/Bubble Sort(in Python).py: -------------------------------------------------------------------------------- 1 | def bubble_sort(arr): 2 | n = len(arr) 3 | # Traverse through all array elements 4 | for i in range(n): 5 | # Last i elements are already in place, so we don't need to check them again 6 | for j in range(0, n - i - 1): 7 | # Swap if the element found is greater than the next element 8 | if arr[j] > arr[j + 1]: 9 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 10 | 11 | # Example usage: 12 | arr = [64, 34, 25, 12, 22, 11, 90] 13 | bubble_sort(arr) 14 | 15 | print("Sorted array is:", arr) 16 | -------------------------------------------------------------------------------- /BubbleSortAlgorithm/README.md: -------------------------------------------------------------------------------- 1 | # Bubble Sort Algorithm 2 | 3 | Bubble Sort is a simple, comparison-based sorting algorithm that compares adjacent elements, and swaps them if they are in the wrong order. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n^2) 8 | Average: O(n^2) 9 | Worst: O(n*(n-1)/2 ) 10 | 11 | ## Space Complexity 12 | 13 | O(1) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a small dataset or sorting an array 18 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | Thank you for your interest in contributing to the Algorithms Collection repository! We appreciate your help in improving and expanding the collection of algorithms. Please follow the guidelines below to ensure a smooth contribution process. 3 | 4 | ## How to Contribute 5 | 1. Fork the repository. 6 | 7 | 3. Create a new branch for your changes. 8 | 9 | 5. Implement the algorithm in the desired programming language(s). Make sure to follow the coding style conventions of the specific language and include comments to explain your code. 10 | 11 | 7. Add a README.md file in the folder of the specific algorithm you are implementing. The README should contain the following information: 12 | 13 | - Algorithm name 14 | - Brief description of the algorithm 15 | - Time complexity 16 | - Space complexity 17 | - Example use case 18 | - Code snippet (optional) 19 | 5. Test your code thoroughly to ensure it is working correctly. 20 | 21 | 6. Commit your changes and push them to your forked repository. 22 | 23 | 7. Create a pull request, providing a detailed description of the changes you've made. 24 | 25 | 8. Wait for a maintainer to review your pull request. They may suggest changes or ask for clarification on certain aspects. Please be patient and address any feedback provided. 26 | 27 | ## Code of Conduct 28 | Please adhere to the following code of conduct while contributing to this repository: 29 | 30 | - Be respectful and considerate towards other contributors. 31 | - Use appropriate language and avoid offensive comments. 32 | - Keep the discussions focused on the topic at hand. 33 | - Be open to constructive criticism and be willing to learn from others. 34 | 35 | By following these guidelines, we can maintain a welcoming and productive environment for all contributors. Thank you for your cooperation! 36 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/C++/Counting-Sort-Algortihm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void counting_sort(std::vector& arr) { 5 | int max = arr[0], min = arr[0]; 6 | 7 | for (int num : arr) { 8 | max = std::max(max, num); 9 | min = std::min(min, num); 10 | } 11 | 12 | int range = max - min + 1; 13 | std::vector count(range, 0); 14 | std::vector output(arr.size()); 15 | 16 | for (int num : arr) 17 | count[num - min]++; 18 | 19 | for (int i = 1; i < range; i++) 20 | count[i] += count[i - 1]; 21 | 22 | for (int i = arr.size() - 1; i >= 0; i--) { 23 | output[count[arr[i] - min] - 1] = arr[i]; 24 | count[arr[i] - min]--; 25 | } 26 | 27 | arr = output; 28 | } 29 | 30 | int main() { 31 | std::vector arr = {4, 2, 2, 8, 3, 3, 1}; 32 | 33 | counting_sort(arr); 34 | 35 | for (int num : arr) 36 | std::cout << num << " "; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/C/Counting-Sort-Algortihm.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/abhaysinghr516/Algorithms/9fea3eabb1596a91c3f8c058d9006f30d64840de/Counting Sort Algortihm/C/Counting-Sort-Algortihm.c -------------------------------------------------------------------------------- /Counting Sort Algortihm/Go/Counting-Sort-Algortihm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func counting_sort(arr []int) { 8 | max, min := arr[0], arr[0] 9 | 10 | for _, num := range arr { 11 | if num > max { 12 | max = num 13 | } 14 | if num < min { 15 | min = num 16 | } 17 | } 18 | 19 | rangeLen := max - min + 1 20 | count := make([]int, rangeLen) 21 | output := make([]int, len(arr)) 22 | 23 | for _, num := range arr { 24 | count[num-min]++ 25 | } 26 | 27 | for i := 1; i < rangeLen; i++ { 28 | count[i] += count[i-1] 29 | } 30 | 31 | for i := len(arr) - 1; i >= 0; i-- { 32 | output[count[arr[i]-min]-1] = arr[i] 33 | count[arr[i]-min]-- 34 | } 35 | 36 | copy(arr, output) 37 | } 38 | 39 | func main() { 40 | arr := []int{4, 2, 2, 8, 3, 3, 1} 41 | 42 | counting_sort(arr) 43 | 44 | for _, num := range arr { 45 | fmt.Printf("%d ", num) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/Java/Counting-Sort-Algortihm.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class CountingSort { 4 | public static void countingSort(int[] arr) { 5 | int max = arr[0], min = arr[0]; 6 | 7 | for (int num : arr) { 8 | max = Math.max(max, num); 9 | min = Math.min(min, num); 10 | } 11 | 12 | int range = max - min + 1; 13 | int[] count = new int[range]; 14 | int[] output = new int[arr.length]; 15 | 16 | for (int num : arr) 17 | count[num - min]++; 18 | 19 | for (int i = 1; i < range; i++) 20 | count[i] += count[i - 1]; 21 | 22 | for (int i = arr.length - 1; i >= 0; i--) { 23 | output[count[arr[i] - min] - 1] = arr[i]; 24 | count[arr[i] - min]--; 25 | } 26 | 27 | System.arraycopy(output, 0, arr, 0, arr.length); 28 | } 29 | 30 | public static void main(String[] args) { 31 | int[] arr = {4, 2, 2, 8, 3, 3, 1}; 32 | 33 | countingSort(arr); 34 | 35 | System.out.println(Arrays.toString(arr)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/JavaScript/Counting-Sort-Algortihm.js: -------------------------------------------------------------------------------- 1 | function countingSort(arr) { 2 | let max = arr[0], min = arr[0]; 3 | 4 | for (const num of arr) { 5 | max = Math.max(max, num); 6 | min = Math.min(min, num); 7 | } 8 | 9 | const range = max - min + 1; 10 | const count = new Array(range).fill(0); 11 | const output = new Array(arr.length).fill(0); 12 | 13 | for (const num of arr) 14 | count[num - min]++; 15 | 16 | for (let i = 1; i < range; i++) 17 | count[i] += count[i - 1]; 18 | 19 | for (let i = arr.length - 1; i >= 0; i--) { 20 | output[count[arr[i] - min] - 1] = arr[i]; 21 | count[arr[i] - min]--; 22 | } 23 | 24 | for (let i = 0; i < arr.length; i++) 25 | arr[i] = output[i]; 26 | } 27 | 28 | const arr = [4, 2, 2, 8, 3, 3, 1]; 29 | 30 | countingSort(arr); 31 | 32 | console.log(arr); 33 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/Python/Counting-Sort-Algortihm.py: -------------------------------------------------------------------------------- 1 | def counting_sort(arr): 2 | max_val, min_val = max(arr), min(arr) 3 | 4 | range_len = max_val - min_val + 1 5 | count = [0] * range_len 6 | output = [0] * len(arr) 7 | 8 | for num in arr: 9 | count[num - min_val] += 1 10 | 11 | for i in range(1, range_len): 12 | count[i] += count[i - 1] 13 | 14 | for i in range(len(arr) - 1, -1, -1): 15 | output[count[arr[i] - min_val] - 1] = arr[i] 16 | count[arr[i] - min_val] -= 1 17 | 18 | for i in range(len(arr)): 19 | arr[i] = output[i] 20 | 21 | arr = [4, 2, 2, 8, 3, 3, 1] 22 | 23 | counting_sort(arr) 24 | 25 | print(arr) 26 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Counting Sort Algorithm 2 | 3 | Counting Sort is a non-comparative sorting algorithm that works by counting the occurrences of each distinct element in the input array and then constructing a sorted output array. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n + k) 8 | Average: O(n + k) 9 | Worst: O(n + k) 10 | 11 | ## Space Complexity 12 | 13 | O(n + k) 14 | 15 | ## Example Use Case 16 | 17 | Sorting integers within a known, small range, such as sorting test scores or sorting characters in a string based on their ASCII values. 18 | -------------------------------------------------------------------------------- /Counting Sort Algortihm/Rust/Counting_Sort_Algorithm.rs: -------------------------------------------------------------------------------- 1 | fn counting_sort(arr: &mut [i32]) { 2 | let mut max = arr[0]; 3 | let mut min = arr[0]; 4 | 5 | // Find the maximum and minimum values in the array 6 | for &num in arr.iter() { 7 | max = max.max(num); 8 | min = min.min(num); 9 | } 10 | 11 | let range = (max - min + 1) as usize; 12 | let mut count = vec![0; range]; 13 | let mut output = vec![0; arr.len()]; 14 | 15 | // Count the occurrences of each element 16 | for &num in arr.iter() { 17 | count[(num - min) as usize] += 1; 18 | } 19 | 20 | // Calculate the cumulative counts 21 | for i in 1..range { 22 | count[i] += count[i - 1]; 23 | } 24 | 25 | // Build the sorted output 26 | for i in (0..arr.len()).rev() { 27 | let num = arr[i]; 28 | let index = (num - min) as usize; 29 | output[count[index] as usize - 1] = num; 30 | count[index] -= 1; 31 | } 32 | 33 | // Copy the sorted elements back to the original array 34 | arr.copy_from_slice(&output); 35 | } 36 | 37 | fn main() { 38 | let mut arr = vec![4, 2, 2, 8, 3, 3, 1]; 39 | counting_sort(&mut arr); 40 | println!("{:?}", arr); 41 | } 42 | -------------------------------------------------------------------------------- /DIjkstra/Readme.md: -------------------------------------------------------------------------------- 1 | # DIJKSTRA ALGORITHM: 2 | USED TO FIND THE DISTANCE AND PATH IN BETWEEN THE NODES. 3 | ### TIME COMPLEXITY: 4 | O(numnode^2) 5 | ### SPACE COMPLEXITY: 6 | O(numnode) 7 | ### EXAMPLE USE CASE: 8 | To find the shortest path to travel. 9 | -------------------------------------------------------------------------------- /DIjkstra/code.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define maxnodes 100 5 | int findmindistance(int dist[], bool visited[], int numnodes) { 6 | int mindist =INT_MAX;//here INT_MAX is a predefined value 7 | int minindex=-1; 8 | for (int v = 0; v < numnodes; v++) { 9 | if (visited[v] == false && dist[v] <= mindist) { 10 | mindist = dist[v]; 11 | minindex = v; 12 | } 13 | } 14 | return minindex; 15 | } 16 | //To find the shortest path following code is used 17 | void printshortestpath(int dist[], int origin[], int xy, int numnodes) { 18 | printf("Vertex\t\tDistance\tPath\n"); 19 | for (int v = 0; v < numnodes; v++) { 20 | printf("%d\t\t%d\t\t", v, dist[v]); 21 | int j = v; 22 | while (j != xy) { 23 | printf("%d <- ", j); 24 | j = origin[j]; 25 | } 26 | printf("%d\n", xy); 27 | } 28 | } 29 | void dijkstra(int graph[maxnodes][maxnodes], int xy, int numnodes) { 30 | int dist[maxnodes]; 31 | bool visited[maxnodes]; 32 | int origin[maxnodes]; 33 | for (int i = 0; i < numnodes; i++) { 34 | dist[i] = INT_MAX; 35 | visited[i] = false; 36 | } 37 | dist[xy] = 0; 38 | origin[xy] = -1; 39 | for (int count = 0; count < numnodes - 1; count++) { 40 | ///find minimum distance between each node 41 | int u = findmindistance(dist, visited, numnodes); 42 | visited[u] = true; 43 | for (int v = 0; v < numnodes; v++) { 44 | if (!visited[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] + 45 | graph[u][v] < dist[v]) { 46 | dist[v] = dist[u] + graph[u][v]; 47 | origin[v] = u; 48 | } 49 | } 50 | } 51 | //Prints the shortest path 52 | printshortestpath(dist, origin, xy, numnodes); 53 | } 54 | int main() { 55 | int numnodes, i, j; 56 | int graph[maxnodes][maxnodes]; 57 | printf("Input the number of nodes: "); 58 | scanf("%d", &numnodes); 59 | printf("Input your adjacency matrix:\n"); 60 | for (i = 0; i < numnodes; i++) { 61 | for (j = 0; j < numnodes; j++) { 62 | scanf("%d", &graph[i][j]); 63 | } 64 | } 65 | int source; 66 | printf("Input the source vertex: "); 67 | scanf("%d", &source); 68 | dijkstra(graph, source, numnodes); 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/C++/Depth-First-Search-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | class Graph { 6 | public: 7 | Graph(int vertices) : vertices(vertices) { 8 | adj_list.resize(vertices); 9 | visited.resize(vertices, false); 10 | } 11 | 12 | void add_edge(int src, int dest) { 13 | adj_list[src].push_back(dest); 14 | adj_list[dest].push_back(src); 15 | } 16 | 17 | void dfs(int vertex) { 18 | visited[vertex] = true; 19 | std::cout << "Visited " << vertex << std::endl; 20 | 21 | for (int adj_vertex : adj_list[vertex]) { 22 | if (!visited[adj_vertex]) { 23 | dfs(adj_vertex); 24 | } 25 | } 26 | } 27 | 28 | private: 29 | int vertices; 30 | std::vector> adj_list; 31 | std::vector visited; 32 | }; 33 | 34 | int main() { 35 | Graph g(6); 36 | 37 | g.add_edge(0, 1); 38 | g.add_edge(0, 2); 39 | g.add_edge(1, 3); 40 | g.add_edge(1, 4); 41 | g.add_edge(2, 4); 42 | g.add_edge(3, 5); 43 | g.add_edge(4, 5); 44 | 45 | g.dfs(0); 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/C/Depth-First-Search-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | typedef struct Node { 6 | int dest; 7 | struct Node* next; 8 | } Node; 9 | 10 | typedef struct Graph { 11 | int vertices; 12 | Node** adj_list; 13 | bool* visited; 14 | } Graph; 15 | 16 | Node* create_node(int dest) { 17 | Node* new_node = (Node*)malloc(sizeof(Node)); 18 | new_node->dest = dest; 19 | new_node->next = NULL; 20 | return new_node; 21 | } 22 | 23 | Graph* create_graph(int vertices) { 24 | Graph* graph = (Graph*)malloc(sizeof(Graph)); 25 | graph->vertices = vertices; 26 | graph->adj_list = (Node**)calloc(vertices, sizeof(Node*)); 27 | graph->visited = (bool*)calloc(vertices, sizeof(bool)); 28 | return graph; 29 | } 30 | 31 | void add_edge(Graph* graph, int src, int dest) { 32 | Node* new_node = create_node(dest); 33 | new_node->next = graph->adj_list[src]; 34 | graph->adj_list[src] = new_node; 35 | 36 | new_node = create_node(src); 37 | new_node->next = graph->adj_list[dest]; 38 | graph->adj_list[dest] = new_node; 39 | } 40 | 41 | void dfs(Graph* graph, int vertex) { 42 | Node* current = graph->adj_list[vertex]; 43 | graph->visited[vertex] = true; 44 | printf("Visited %d\n", vertex); 45 | 46 | while (current) { 47 | if (!graph->visited[current->dest]) { 48 | dfs(graph, current->dest); 49 | } 50 | current = current->next; 51 | } 52 | } 53 | 54 | int main() { 55 | Graph* g = create_graph(6); 56 | 57 | add_edge(g, 0, 1); 58 | add_edge(g, 0, 2); 59 | add_edge(g, 1, 3); 60 | add_edge(g, 1, 4); 61 | add_edge(g, 2, 4); 62 | add_edge(g, 3, 5); 63 | add_edge(g, 4, 5); 64 | 65 | dfs(g, 0); 66 | 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/Go/Depth-First-Search-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type Graph struct { 8 | vertices int 9 | adj_list []([]int) 10 | visited []bool 11 | } 12 | 13 | func newGraph(vertices int) *Graph { 14 | return &Graph{ 15 | vertices: vertices, 16 | adj_list: make([]([]int), vertices), 17 | visited: make([]bool, vertices), 18 | } 19 | } 20 | 21 | func (g *Graph) addEdge(src, dest int) { 22 | g.adj_list[src] = append(g.adj_list[src], dest) 23 | g.adj_list[dest] = append(g.adj_list[dest], src) 24 | } 25 | 26 | func (g *Graph) dfs(vertex int) { 27 | g.visited[vertex] = true 28 | fmt.Printf("Visited %d\n", vertex) 29 | 30 | for _, adj_vertex := range g.adj_list[vertex] { 31 | if !g.visited[adj_vertex] { 32 | g.dfs(adj_vertex) 33 | } 34 | } 35 | } 36 | 37 | func main() { 38 | g := newGraph(6) 39 | 40 | g.addEdge(0, 1) 41 | g.addEdge(0, 2) 42 | g.addEdge(1, 3) 43 | g.addEdge(1, 4) 44 | g.addEdge(2, 4) 45 | g.addEdge(3, 5) 46 | g.addEdge(4, 5) 47 | 48 | g.dfs(0) 49 | } 50 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/Java/Depth-First-Search-Algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.List; 3 | 4 | public class DepthFirstSearch { 5 | static class Graph { 6 | int vertices; 7 | List> adjList; 8 | boolean[] visited; 9 | 10 | public Graph(int vertices) { 11 | this.vertices = vertices; 12 | adjList = new ArrayList<>(vertices); 13 | visited = new boolean[vertices]; 14 | 15 | for (int i = 0; i < vertices; i++) { 16 | adjList.add(new ArrayList<>()); 17 | } 18 | } 19 | 20 | public void addEdge(int src, int dest) { 21 | adjList.get(src).add(dest); 22 | adjList.get(dest).add(src); 23 | } 24 | 25 | public void dfs(int vertex) { 26 | visited[vertex] = true; 27 | System.out.println("Visited " + vertex); 28 | 29 | for (int adjVertex : adjList.get(vertex)) { 30 | if (!visited[adjVertex]) { 31 | dfs(adjVertex); 32 | } 33 | } 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | Graph g = new Graph(6); 39 | 40 | g.addEdge(0, 1); 41 | g.addEdge(0, 2); 42 | g.addEdge(1, 3); 43 | g.addEdge(1, 4); 44 | g.addEdge(2, 4); 45 | g.addEdge(3, 5); 46 | g.addEdge(4, 5); 47 | 48 | g.dfs(0); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/JavaScript/Depth-First-Search-Algorithm.js: -------------------------------------------------------------------------------- 1 | class Graph { 2 | constructor(vertices) { 3 | this.vertices = vertices; 4 | this.adjList = new Array(vertices).fill(null).map(() => []); 5 | this.visited = new Array(vertices).fill(false); 6 | } 7 | 8 | addEdge(src, dest) { 9 | this.adjList[src].push(dest); 10 | this.adjList[dest].push(src); 11 | } 12 | 13 | dfs(vertex) { 14 | this.visited[vertex] = true; 15 | console.log("Visited", vertex); 16 | 17 | for (const adjVertex of this.adjList[vertex]) { 18 | if (!this.visited[adjVertex]) { 19 | this.dfs(adjVertex); 20 | } 21 | } 22 | } 23 | } 24 | 25 | const g = new Graph(6); 26 | 27 | g.addEdge(0, 1); 28 | g.addEdge(0, 2); 29 | g.addEdge(1, 3); 30 | g.addEdge(1, 4); 31 | g.addEdge(2, 4); 32 | g.addEdge(3, 5); 33 | g.addEdge(4, 5); 34 | 35 | g.dfs(0); 36 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/Python/Depth-First-Search-Algorithm.py: -------------------------------------------------------------------------------- 1 | class Graph: 2 | def __init__(self, vertices): 3 | self.vertices = vertices 4 | self.adj_list = [[] for _ in range(vertices)] 5 | self.visited = [False] * vertices 6 | 7 | def add_edge(self, src, dest): 8 | self.adj_list[src].append(dest) 9 | self.adj_list[dest].append(src) 10 | 11 | def dfs(self, vertex): 12 | self.visited[vertex] = True 13 | print(f"Visited {vertex}") 14 | 15 | for adj_vertex in self.adj_list[vertex]: 16 | if not self.visited[adj_vertex]: 17 | self.dfs(adj_vertex) 18 | 19 | g = Graph(6) 20 | 21 | g.add_edge(0, 1) 22 | g.add_edge(0, 2) 23 | g.add_edge(1, 3) 24 | g.add_edge(1, 4) 25 | g.add_edge(2, 4) 26 | g.add_edge(3, 5) 27 | g.add_edge(4, 5) 28 | 29 | g.dfs(0) 30 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Depth-First Search (DFS) Algorithm 2 | 3 | Depth-First Search (DFS) is a graph traversal algorithm that explores as far as possible along each branch before backtracking. It can be implemented using either recursion or an explicit stack data structure. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V + E) 8 | Average: O(V + E) 9 | Worst: O(V + E) 10 | 11 | ## Space Complexity 12 | 13 | O(V) 14 | 15 | ## Example Use Case 16 | 17 | Finding a path between two vertices in a graph, such as solving a maze or determining whether a sequence of dependencies can be satisfied in a build system. 18 | -------------------------------------------------------------------------------- /Depth First Search(DFS) Algorithm/Rust/Depth_Firtst_Search_Algorithm.rs: -------------------------------------------------------------------------------- 1 | struct Graph { 2 | vertices: usize, 3 | adj_list: Vec>, 4 | } 5 | 6 | impl Graph { 7 | fn new(vertices: usize) -> Self { 8 | let adj_list = vec![vec![]; vertices]; 9 | Graph { 10 | vertices, 11 | adj_list, 12 | } 13 | } 14 | 15 | fn add_edge(&mut self, src: usize, dest: usize) { 16 | self.adj_list[src].push(dest); 17 | self.adj_list[dest].push(src); 18 | } 19 | 20 | fn dfs(&self, vertex: usize, visited: &mut Vec) { 21 | visited[vertex] = true; 22 | println!("Visited {}", vertex); 23 | 24 | for &adj_vertex in &self.adj_list[vertex] { 25 | if !visited[adj_vertex] { 26 | self.dfs(adj_vertex, visited); 27 | } 28 | } 29 | } 30 | } 31 | 32 | fn main() { 33 | let mut g = Graph::new(6); 34 | 35 | g.add_edge(0, 1); 36 | g.add_edge(0, 2); 37 | g.add_edge(1, 3); 38 | g.add_edge(1, 4); 39 | g.add_edge(2, 4); 40 | g.add_edge(3, 5); 41 | g.add_edge(4, 5); 42 | 43 | let mut visited = vec![false; g.vertices]; 44 | g.dfs(0, &mut visited); 45 | } 46 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm/C++/Dijkstra's-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define V 9 6 | 7 | int min_distance(const std::vector& dist, const std::vector& spt_set) { 8 | int min = std::numeric_limits::max(), min_index; 9 | for (int v = 0; v < V; v++) { 10 | if (spt_set[v] == false && dist[v] <= min) { 11 | min = dist[v]; 12 | min_index = v; 13 | } 14 | } 15 | 16 | return min_index; 17 | 18 | } 19 | 20 | void print_solution(const std::vector& dist) { 21 | std::cout << "Vertex \t Distance from Source\n"; 22 | for (int i = 0; i < V; i++) { 23 | std::cout << i << " \t\t " << dist[i] << '\n'; 24 | } 25 | } 26 | 27 | void dijkstra(const std::vector>& graph, int src) { 28 | std::vector dist(V, std::numeric_limits::max()); 29 | std::vector spt_set(V, false); 30 | 31 | dist[src] = 0; 32 | 33 | for (int count = 0; count < V - 1; count++) { 34 | int u = min_distance(dist, spt_set); 35 | spt_set[u] = true; 36 | 37 | for (int v = 0; v < V; v++) { 38 | if (!spt_set[v] && graph[u][v] && dist[u] != std::numeric_limits::max() && 39 | dist[u] + graph[u][v] < dist[v]) { 40 | dist[v] = dist[u] + graph[u][v]; 41 | } 42 | } 43 | } 44 | 45 | print_solution(dist); 46 | } 47 | 48 | int main() { 49 | std::vector> graph = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, 50 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 51 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 52 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 53 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 54 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 55 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 56 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 57 | {0, 0, 2, 0, 0, 0, 6, 7, 0}}; 58 | 59 | dijkstra(graph, 0); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Dijkstra's Algorithm/C/Dijkstra's-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #define V 9 6 | 7 | int min_distance(int dist[], bool spt_set[]) { 8 | int min = INT_MAX, min_index; 9 | for (int v = 0; v < V; v++) { 10 | if (spt_set[v] == false && dist[v] <= min) { 11 | min = dist[v]; 12 | min_index = v; 13 | } 14 | } 15 | return min_index; 16 | } 17 | 18 | void print_solution(int dist[]) { 19 | printf("Vertex \t Distance from Source\n"); 20 | for (int i = 0; i < V; i++) { 21 | printf("%d \t\t %d\n", i, dist[i]); 22 | } 23 | } 24 | 25 | void dijkstra(int graph[V][V], int src) { 26 | int dist[V]; 27 | bool spt_set[V]; 28 | 29 | for (int i = 0; i < V; i++) { 30 | dist[i] = INT_MAX; 31 | spt_set[i] = false; 32 | } 33 | 34 | dist[src] = 0; 35 | 36 | for (int count = 0; count < V - 1; count++) { 37 | int u = min_distance(dist, spt_set); 38 | spt_set[u] = true; 39 | 40 | for (int v = 0; v < V; v++) { 41 | if (!spt_set[v] && graph[u][v] && dist[u] != INT_MAX && 42 | dist[u] + graph[u][v] < dist[v]) { 43 | dist[v] = dist[u] + graph[u][v]; 44 | } 45 | } 46 | } 47 | 48 | print_solution(dist); 49 | } 50 | 51 | int main() { 52 | int graph[V][V] = {{0, 4, 0, 0, 0, 0, 0, 8, 0}, 53 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 54 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 55 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 56 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 57 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 58 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 59 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 60 | {0, 0, 2, 0, 0, 0, 6, 7, 0}}; 61 | 62 | dijkstra(graph, 0); 63 | 64 | return 0; 65 | } 66 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm/Go/Dijkstra's-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | const V = 9 9 | 10 | func minDistance(dist []int, sptSet []bool) int { 11 | min := math.MaxInt32 12 | minIndex := -1 13 | 14 | for v := 0; v < V; v++ { 15 | if !sptSet[v] && dist[v] <= min { 16 | min = dist[v] 17 | minIndex = v 18 | } 19 | } 20 | 21 | return minIndex 22 | } 23 | 24 | func printSolution(dist []int) { 25 | fmt.Println("Vertex \t Distance from Source") 26 | for i := 0; i < V; i++ { 27 | fmt.Printf("%d \t\t %d\n", i, dist[i]) 28 | } 29 | } 30 | 31 | func dijkstra(graph [][]int, src int) { 32 | dist := make([]int, V) 33 | sptSet := make([]bool, V) 34 | 35 | for i := 0; i < V; i++ { 36 | dist[i] = math.MaxInt32 37 | sptSet[i] = false 38 | } 39 | 40 | dist[src] = 0 41 | 42 | for count := 0; count < V-1; count++ { 43 | u := minDistance(dist, sptSet) 44 | sptSet[u] = true 45 | 46 | for v := 0; v < V; v++ { 47 | if !sptSet[v] && graph[u][v] != 0 && dist[u] != math.MaxInt32 && dist[u]+graph[u][v] < dist[v] { 48 | dist[v] = dist[u] + graph[u][v] 49 | } 50 | } 51 | } 52 | 53 | printSolution(dist) 54 | } 55 | 56 | func main() { 57 | graph := [][]int{ 58 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 59 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 60 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 61 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 62 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 63 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 64 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 65 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 66 | {0, 0, 2, 0, 0, 0, 6, 7, 0}, 67 | } 68 | 69 | dijkstra(graph, 0) 70 | 71 | } 72 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm/Java/Dijkstra's-Algorithm.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class DijkstraAlgorithm { 4 | private static final int V = 9; 5 | 6 | private static int minDistance(int[] dist, boolean[] sptSet) { 7 | int min = Integer.MAX_VALUE; 8 | int minIndex = -1; 9 | 10 | for (int v = 0; v < V; v++) { 11 | if (!sptSet[v] && dist[v] <= min) { 12 | min = dist[v]; 13 | minIndex = v; 14 | } 15 | } 16 | 17 | return minIndex; 18 | } 19 | 20 | private static void printSolution(int[] dist) { 21 | System.out.println("Vertex \t Distance from Source"); 22 | for (int i = 0; i < V; i++) { 23 | System.out.println(i + " \t\t " + dist[i]); 24 | } 25 | } 26 | 27 | public static void dijkstra(int[][] graph, int src) { 28 | int[] dist = new int[V]; 29 | boolean[] sptSet = new boolean[V]; 30 | 31 | Arrays.fill(dist, Integer.MAX_VALUE); 32 | Arrays.fill(sptSet, false); 33 | 34 | dist[src] = 0; 35 | 36 | for (int count = 0; count < V - 1; count++) { 37 | int u = minDistance(dist, sptSet); 38 | sptSet[u] = true; 39 | 40 | for (int v = 0; v < V; v++) { 41 | if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE && 42 | dist[u] + graph[u][v] < dist[v]) { 43 | dist[v] = dist[u] + graph[u][v]; 44 | } 45 | } 46 | } 47 | 48 | printSolution(dist); 49 | } 50 | 51 | public static void main(String[] args) { 52 | int[][] graph = { 53 | {0, 4, 0, 0, 0, 0, 0, 8, 0}, 54 | {4, 0, 8, 0, 0, 0, 0, 11, 0}, 55 | {0, 8, 0, 7, 0, 4, 0, 0, 2}, 56 | {0, 0, 7, 0, 9, 14, 0, 0, 0}, 57 | {0, 0, 0, 9, 0, 10, 0, 0, 0}, 58 | {0, 0, 4, 14, 10, 0, 2, 0, 0}, 59 | {0, 0, 0, 0, 0, 2, 0, 1, 6}, 60 | {8, 11, 0, 0, 0, 0, 1, 0, 7}, 61 | {0, 0, 2, 0, 0, 0, 6, 7, 0}, 62 | }; 63 | 64 | dijkstra(graph, 0); 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm/JavaScript/Dijkstra's-Algorithm.js: -------------------------------------------------------------------------------- 1 | const V = 9; 2 | 3 | function minDistance(dist, sptSet) { 4 | let min = Number.MAX_VALUE; 5 | let minIndex = -1; 6 | 7 | for (let v = 0; v < V; v++) { 8 | if (!sptSet[v] && dist[v] <= min) { 9 | min = dist[v]; 10 | minIndex = v; 11 | } 12 | } 13 | 14 | return minIndex; 15 | } 16 | 17 | function printSolution(dist) { 18 | console.log("Vertex \t Distance from Source"); 19 | for (let i = 0; i < V; i++) { 20 | console.log(i + " \t\t " + dist[i]); 21 | } 22 | } 23 | 24 | function dijkstra(graph, src) { 25 | let dist = new Array(V).fill(Number.MAX_VALUE); 26 | let sptSet = new Array(V).fill(false); 27 | 28 | dist[src] = 0; 29 | 30 | for (let count = 0; count < V - 1; count++) { 31 | let u = minDistance(dist, sptSet); 32 | sptSet[u] = true; 33 | 34 | for (let v = 0; v < V; v++) { 35 | if (!sptSet[v] && graph[u][v] !== 0 && dist[u] !== Number.MAX_VALUE && 36 | dist[u] + graph[u][v] < dist[v]) { 37 | dist[v] = dist[u] + graph[u][v]; 38 | } 39 | } 40 | } 41 | 42 | printSolution(dist); 43 | } 44 | 45 | const graph = [ 46 | [0, 4, 0, 0, 0, 0, 0, 8, 0], 47 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 48 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 49 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 50 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 51 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 52 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 53 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 54 | [0, 0, 2, 0, 0, 0, 6, 7, 0], 55 | ]; 56 | 57 | dijkstra(graph, 0); -------------------------------------------------------------------------------- /Dijkstra's Algorithm/Python/Dijkstra's-Algorithm.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | V = 9 4 | 5 | def min_distance(dist, spt_set): 6 | min_val = sys.maxsize 7 | min_index = -1 8 | 9 | for v in range(V): 10 | if not spt_set[v] and dist[v] <= min_val: 11 | min_val = dist[v] 12 | min_index = v 13 | 14 | return min_index 15 | 16 | def print_solution(dist): 17 | print("Vertex \t Distance from Source") 18 | for i in range(V): 19 | print(i, "\t\t", dist[i]) 20 | 21 | def dijkstra(graph, src): 22 | dist = [sys.maxsize] * V 23 | spt_set = [False] * V 24 | 25 | dist[src] = 0 26 | 27 | for _ in range(V - 1): 28 | u = min_distance(dist, spt_set) 29 | spt_set[u] = True 30 | 31 | for v in range(V): 32 | if not spt_set[v] and graph[u][v] != 0 and dist[u] != sys.maxsize and dist[u] + graph[u][v] < dist[v]: 33 | dist[v] = dist[u] + graph[u][v] 34 | 35 | print_solution(dist) 36 | 37 | graph = [ 38 | [0, 4, 0, 0, 0, 0, 0, 8, 0], 39 | [4, 0, 8, 0, 0, 0, 0, 11, 0], 40 | [0, 8, 0, 7, 0, 4, 0, 0, 2], 41 | [0, 0, 7, 0, 9, 14, 0, 0, 0], 42 | [0, 0, 0, 9, 0, 10, 0, 0, 0], 43 | [0, 0, 4, 14, 10, 0, 2, 0, 0], 44 | [0, 0, 0, 0, 0, 2, 0, 1, 6], 45 | [8, 11, 0, 0, 0, 0, 1, 0, 7], 46 | [0, 0, 2, 0, 0, 0, 6, 7, 0], 47 | ] 48 | 49 | dijkstra(graph, 0) -------------------------------------------------------------------------------- /Dijkstra's Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Dijkstra's Algorithm 2 | 3 | Dijkstra's Algorithm is a graph search algorithm that finds the shortest path from a source vertex to all other vertices in a weighted, directed graph with non-negative edge weights. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V^2) with an adjacency matrix, O(V + E _ log(V)) with an adjacency list and a min-priority queue 8 | Average: O(V^2) with an adjacency matrix, O(V + E _ log(V)) with an adjacency list and a min-priority queue 9 | Worst: O(V^2) with an adjacency matrix, O(V + E \* log(V)) with an adjacency list and a min-priority queue 10 | 11 | ## Space Complexity 12 | 13 | O(V) 14 | 15 | ## Example Use Case 16 | 17 | Finding the shortest path from a source vertex to all other vertices in a graph with non-negative edge weights, such as shortest driving times between cities or lowest costs in a transportation network. 18 | -------------------------------------------------------------------------------- /Dijkstra's Algorithm/Rust/Dijkstra's-Algorithm.rs: -------------------------------------------------------------------------------- 1 | use std::collections::BinaryHeap; 2 | use std::collections::HashMap; 3 | use std::collections::HashSet; 4 | 5 | #[derive(Debug, Eq, PartialEq, PartialOrd, Ord, Clone)] 6 | struct Node { 7 | id: usize, 8 | cost: i32, 9 | } 10 | 11 | impl Node { 12 | fn new(id: usize, cost: i32) -> Node { 13 | Node { id, cost } 14 | } 15 | } 16 | 17 | fn dijkstra(graph: &HashMap>, start: usize) -> HashMap { 18 | let mut distance: HashMap = graph 19 | .keys() 20 | .map(|&id| (id, i32::max_value())) 21 | .collect(); 22 | distance.insert(start, 0); 23 | 24 | let mut visited: HashSet = HashSet::new(); 25 | 26 | let mut priority_queue: BinaryHeap = BinaryHeap::new(); 27 | priority_queue.push(Node::new(start, 0)); 28 | 29 | while let Some(Node { id, cost }) = priority_queue.pop() { 30 | if visited.contains(&id) { 31 | continue; 32 | } 33 | 34 | visited.insert(id); 35 | 36 | for &(neighbor, weight) in &graph[&id] { 37 | let new_cost = cost + weight; 38 | if new_cost < distance[&neighbor] { 39 | distance.insert(neighbor, new_cost); 40 | priority_queue.push(Node::new(neighbor, new_cost)); 41 | } 42 | } 43 | } 44 | 45 | distance 46 | } 47 | 48 | fn main() { 49 | let mut graph: HashMap > = HashMap::new(); 50 | graph.insert(0, vec![(1, 4), (2, 2)]); 51 | graph.insert(1, vec![(3, 5)]); 52 | graph.insert(2, vec![(1, 1), (3, 8)]); 53 | graph.insert(3, vec![]); 54 | 55 | let start_node = 0; 56 | let distances = dijkstra(&graph, start_node); 57 | 58 | for (node, distance) in distances.iter() { 59 | println!("Shortest distance from node {} to node {}: {}", start_node, node, distance); 60 | } 61 | } -------------------------------------------------------------------------------- /Eulic's Algorithm/C++/Eulic's-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int gcd(int a, int b) { 5 | if (b == 0) 6 | return a; 7 | else 8 | return gcd(b, a % b); 9 | } 10 | 11 | int main() { 12 | int a = 60, b = 48; 13 | cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << endl; 14 | return 0; 15 | } 16 | -------------------------------------------------------------------------------- /Eulic's Algorithm/C/Eulic's-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int gcd(int a, int b) { 4 | if (b == 0) 5 | return a; 6 | else 7 | return gcd(b, a % b); 8 | } 9 | 10 | int main() { 11 | int a = 60, b = 48; 12 | printf("GCD of %d and %d is %d\n", a, b, gcd(a, b)); 13 | return 0; 14 | } 15 | -------------------------------------------------------------------------------- /Eulic's Algorithm/Go/Eulic's-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func gcd(a int, b int) int { 6 | if b == 0 { 7 | return a 8 | } 9 | return gcd(b, a % b) 10 | } 11 | 12 | func main() { 13 | a := 48 14 | b := 18 15 | fmt.Printf("GCD of %d and %d is %d\n", a, b, gcd(a, b)) 16 | } 17 | -------------------------------------------------------------------------------- /Eulic's Algorithm/Java/Eulic's-Algorithm.java: -------------------------------------------------------------------------------- 1 | public class EuclidsAlgorithm { 2 | public static int gcd(int a, int b) { 3 | if (b == 0) { 4 | return a; 5 | } 6 | return gcd(b, a % b); 7 | } 8 | 9 | public static void main(String[] args) { 10 | int a = 48; 11 | int b = 18; 12 | System.out.printf("GCD of %d and %d is %d\n", a, b, gcd(a, b)); 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /Eulic's Algorithm/JavaScript/Eulic's-Algorithm.js: -------------------------------------------------------------------------------- 1 | function gcd(a, b) { 2 | if (b === 0) { 3 | return a; 4 | } 5 | return gcd(b, a % b); 6 | } 7 | 8 | const a = 48; 9 | const b = 18; 10 | console.log(`GCD of ${a} and ${b} is ${gcd(a, b)}`); 11 | -------------------------------------------------------------------------------- /Eulic's Algorithm/Python/Eulic's-Algorithm.py: -------------------------------------------------------------------------------- 1 | def gcd(a, b): 2 | if b == 0: 3 | return a 4 | return gcd(b, a % b) 5 | 6 | a = 48 7 | b = 18 8 | print(f"GCD of {a} and {b} is {gcd(a, b)}") 9 | -------------------------------------------------------------------------------- /Eulic's Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Euclid's Algorithm 2 | 3 | Euclid's Algorithm is an efficient method for computing the greatest common divisor (GCD) of two integers. It is based on the principle that the GCD of two numbers does not change if the larger number is replaced by its difference with the smaller number. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(log(min(a, b))) 8 | Average: O(log(min(a, b))) 9 | Worst: O(log(min(a, b))) 10 | 11 | ## Space Complexity 12 | 13 | O(1) for the iterative implementation 14 | O(log(min(a, b))) for the recursive implementation 15 | 16 | ## Example Use Case 17 | 18 | Calculating the GCD of two numbers, such as simplifying fractions or determining the coprimality of integers. 19 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/C++/Flood-Fill-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define M 8 3 | #define N 8 4 | 5 | void floodFillUtil(int screen[M][N], int x, int y, int prevC, int newC) { 6 | if (x < 0 || x >= M || y < 0 || y >= N) 7 | return; 8 | if (screen[x][y] != prevC) 9 | return; 10 | screen[x][y] = newC; 11 | floodFillUtil(screen, x+1, y, prevC, newC); 12 | floodFillUtil(screen, x-1, y, prevC, newC); 13 | floodFillUtil(screen, x, y+1, prevC, newC); 14 | floodFillUtil(screen, x, y-1, prevC, newC); 15 | } 16 | 17 | void floodFill(int screen[M][N], int x, int y, int newC) { 18 | int prevC = screen[x][y]; 19 | floodFillUtil(screen, x, y, prevC, newC); 20 | } 21 | 22 | int main() { 23 | int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, 24 | {1, 1, 1, 1, 1, 1, 0, 0}, 25 | {1, 0, 0, 1, 1, 0, 1, 1}, 26 | {1, 2, 2, 2, 2, 0, 1, 0}, 27 | {1, 1, 1, 2, 2, 0, 1, 0}, 28 | {1, 1, 1, 2, 2, 2, 2, 0}, 29 | {1, 1, 1, 1, 1, 2, 1, 1}, 30 | {1, 1, 1, 1, 1, 2, 2, 1}}; 31 | int x = 4, y = 4, newC = 3; 32 | floodFill(screen, x, y, newC); 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/C/Flood-Fill-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define M 8 4 | #define N 8 5 | 6 | void floodFillUtil(int screen[M][N], int x, int y, int prevC, int newC) { 7 | if (x < 0 || x >= M || y < 0 || y >= N) 8 | return; 9 | if (screen[x][y] != prevC) 10 | return; 11 | screen[x][y] = newC; 12 | floodFillUtil(screen, x+1, y, prevC, newC); 13 | floodFillUtil(screen, x-1, y, prevC, newC); 14 | floodFillUtil(screen, x, y+1, prevC, newC); 15 | floodFillUtil(screen, x, y-1, prevC, newC); 16 | } 17 | 18 | void floodFill(int screen[M][N], int x, int y, int newC) { 19 | int prevC = screen[x][y]; 20 | floodFillUtil(screen, x, y, prevC, newC); 21 | } 22 | 23 | int main() { 24 | int screen[M][N] = {{1, 1, 1, 1, 1, 1, 1, 1}, 25 | {1, 1, 1, 1, 1, 1, 0, 0}, 26 | {1, 0, 0, 1, 1, 0, 1, 1}, 27 | {1, 2, 2, 2, 2, 0, 1, 0}, 28 | {1, 1, 1, 2, 2, 0, 1, 0}, 29 | {1, 1, 1, 2, 2, 2, 2, 0}, 30 | {1, 1, 1, 1, 1, 2, 1, 1}, 31 | {1, 1, 1, 1, 1, 2, 2, 1}}; 32 | int x = 4, y = 4, newC = 3; 33 | floodFill(screen, x, y, newC); 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/Go/Flood-Fill-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func floodFill(screen [][]int, x int, y int, prevColor int, newColor int) { 6 | if x < 0 || x >= len(screen) || y < 0 || y >= len(screen[0]) || screen[x][y] != prevColor { 7 | return 8 | } 9 | 10 | screen[x][y] = newColor 11 | 12 | floodFill(screen, x+1, y, prevColor, newColor) 13 | floodFill(screen, x-1, y, prevColor, newColor) 14 | floodFill(screen, x, y+1, prevColor, newColor) 15 | floodFill(screen, x, y-1, prevColor, newColor) 16 | } 17 | 18 | func main() { 19 | screen := [][]int{ 20 | {1, 1, 1, 1, 0, 0, 1, 1}, 21 | {1, 1, 1, 1, 0, 0, 1, 1}, 22 | {1, 0, 0, 1, 1, 1, 1, 1}, 23 | {1, 2, 2, 2, 2, 2, 2, 1}, 24 | {1, 1, 1, 2, 2, 2, 1, 0}, 25 | {1, 1, 1, 2, 2, 2, 1, 0}, 26 | {1, 1, 1, 1, 1, 1, 1, 1}, 27 | {1, 1, 1, 1, 1, 1, 0, 0}, 28 | } 29 | 30 | x := 4 31 | y := 4 32 | prevColor := 2 33 | newColor := 3 34 | floodFill(screen, x, y, prevColor, newColor) 35 | 36 | for _, row := range screen { 37 | fmt.Println(row) 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/Java/Flood-Fill-Algorithm.java: -------------------------------------------------------------------------------- 1 | class FloodFill { 2 | private static int M = 8; 3 | private static int N = 8; 4 | 5 | private static void floodFillUtil(int[][] screen, int x, int y, int prevC, int newC) { 6 | if (x < 0 || x >= M || y < 0 || y >= N) 7 | return; 8 | if (screen[x][y] != prevC) 9 | return; 10 | screen[x][y] = newC; 11 | floodFillUtil(screen, x+1, y, prevC, newC); 12 | floodFillUtil(screen, x-1, y, prevC, newC); 13 | floodFillUtil(screen, x, y+1, prevC, newC); 14 | floodFillUtil(screen, x, y-1, prevC, newC); 15 | } 16 | 17 | public static void floodFill(int[][] screen, int x, int y, int newC) { 18 | int prevC = screen[x][y]; 19 | floodFillUtil(screen, x, y, prevC, newC); 20 | } 21 | 22 | public static void main(String[] args) { 23 | int[][] screen = {{1, 1, 1, 1, 1, 1, 1, 1}, 24 | {1, 1, 1, 1, 1, 1, 0, 0}, 25 | {1, 0, 0, 1, 1, 0, 1, 1}, 26 | {1, 2, 2, 2, 2, 0, 1, 0}, 27 | {1, 1, 1, 2, 2, 0, 1, 0}, 28 | {1, 1, 1, 2, 2, 2, 2, 0}, 29 | {1, 1, 1, 1, 1, 2, 1, 1}, 30 | {1, 1, 1, 1, 1, 2, 2, 1}}; 31 | int x = 4, y = 4, newC = 3; 32 | floodFill(screen, x, y, newC); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/JavaScript/Flood-Fill-Algorithm.js: -------------------------------------------------------------------------------- 1 | function floodFill(screen, x, y, prevColor, newColor) { 2 | if (x < 0 || x >= screen.length || y < 0 || y >= screen[0].length || screen[x][y] !== prevColor) { 3 | return; 4 | } 5 | 6 | screen[x][y] = newColor; 7 | 8 | floodFill(screen, x + 1, y, prevColor, newColor); 9 | floodFill(screen, x - 1, y, prevColor, newColor); 10 | floodFill(screen, x, y + 1, prevColor, newColor); 11 | floodFill(screen, x, y - 1, prevColor, newColor); 12 | } 13 | 14 | const screen = [ 15 | [1, 1, 1, 1, 0, 0, 1, 1], 16 | [1, 1, 1, 1, 0, 0, 1, 1], 17 | [1, 0, 0, 1, 1, 1, 1, 1], 18 | [1, 2, 2, 2, 2, 2, 2, 1], 19 | [1, 1, 1, 2, 2, 2, 1, 0], 20 | [1, 1, 1, 2, 2, 2, 1, 0], 21 | [1, 1, 1, 1, 1, 1, 1, 1], 22 | [1, 1, 1, 1, 1, 1, 0, 0], 23 | ]; 24 | 25 | const x = 4; 26 | const y = 4; 27 | const prevColor = 2; 28 | const newColor = 3; 29 | floodFill(screen, x, y, prevColor, newColor); 30 | 31 | console.log(screen); 32 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/Python/Flood-Fill-Algorithm.py: -------------------------------------------------------------------------------- 1 | def flood_fill(screen, x, y, prev_color, new_color): 2 | if x < 0 or x >= len(screen) or y < 0 or y >= len(screen[0]) or screen[x][y] != prev_color: 3 | return 4 | 5 | screen[x][y] = new_color 6 | 7 | flood_fill(screen, x + 1, y, prev_color, new_color) 8 | flood_fill(screen, x - 1, y, prev_color, new_color) 9 | flood_fill(screen, x, y + 1, prev_color, new_color) 10 | flood_fill(screen, x, y - 1, prev_color, new_color) 11 | 12 | screen = [ 13 | [1, 1, 1, 1, 0, 0, 1, 1], 14 | [1, 1, 1, 1, 0, 0, 1, 1], 15 | [1, 0, 0, 1, 1, 1, 1, 1], 16 | [1, 2, 2, 2, 2, 2, 2, 1], 17 | [1, 1, 1, 2, 2, 2, 1, 0], 18 | [1, 1, 1, 2, 2, 2, 1, 0], 19 | [1, 1, 1, 1, 1, 1, 1, 1], 20 | [1, 1, 1, 1, 1, 1, 0, 0], 21 | ] 22 | 23 | x = 4 24 | y = 4 25 | prev_color = 2 26 | new_color = 3 27 | flood_fill(screen, x, y, prev_color, new_color) 28 | 29 | for row in screen: 30 | print(row) 31 | -------------------------------------------------------------------------------- /Flood Fill Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Flood Fill Algorithm 2 | 3 | The Flood Fill algorithm is used to determine the area connected to a given node in a two-dimensional array or matrix. It can be implemented using either Depth-First Search (DFS) or Breadth-First Search (BFS) and is often used in image processing or maze-solving applications. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n) 8 | Average: O(n) 9 | Worst: O(n) 10 | 11 | ## Space Complexity 12 | 13 | O(n) 14 | 15 | ## Example Use Case 16 | 17 | Filling a region with a specific color in a paint application or identifying connected components in an image for object recognition. 18 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/C++/Floyd-Warshall-Algorithm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define V 4 5 | #define INF 99999 6 | 7 | using namespace std; 8 | 9 | void printSolution(int dist[][V]); 10 | 11 | void floydWarshall(int graph[][V]) { 12 | int dist[V][V], i, j, k; 13 | 14 | for (i = 0; i < V; i++) 15 | for (j = 0; j < V; j++) 16 | dist[i][j] = graph[i][j]; 17 | 18 | for (k = 0; k < V; k++) { 19 | for (i = 0; i < V; i++) { 20 | for (j = 0; j < V; j++) { 21 | if (dist[i][k] + dist[k][j] < dist[i][j]) 22 | dist[i][j] = dist[i][k] + dist[k][j]; 23 | } 24 | } 25 | } 26 | 27 | printSolution(dist); 28 | } 29 | 30 | void printSolution(int dist[][V]) { 31 | cout << "Following matrix shows the shortest distances between every pair of vertices:\n"; 32 | for (int i = 0; i < V; i++) { 33 | for (int j = 0; j < V; j++) { 34 | if (dist[i][j] == INF) 35 | cout << "INF" << "\t"; 36 | else 37 | cout << dist[i][j] << "\t"; 38 | } 39 | cout << endl; 40 | } 41 | } 42 | 43 | int main() { 44 | int graph[V][V] = { {0, 5, INF, 10}, 45 | {INF, 0, 3, INF}, 46 | {INF, INF, 0, 1}, 47 | {INF, INF, INF, 0} }; 48 | 49 | floydWarshall(graph); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/C/Floyd-Warshall-Algorithm.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | #define V 4 5 | #define INF 99999 6 | 7 | void printSolution(int dist[][V]); 8 | 9 | void floydWarshall(int graph[][V]) { 10 | int dist[V][V], i, j, k; 11 | 12 | for (i = 0; i < V; i++) 13 | for (j = 0; j < V; j++) 14 | dist[i][j] = graph[i][j]; 15 | 16 | for (k = 0; k < V; k++) { 17 | for (i = 0; i < V; i++) { 18 | for (j = 0; j < V; j++) { 19 | if (dist[i][k] + dist[k][j] < dist[i][j]) 20 | dist[i][j] = dist[i][k] + dist[k][j]; 21 | } 22 | } 23 | } 24 | 25 | printSolution(dist); 26 | } 27 | 28 | void printSolution(int dist[][V]) { 29 | printf("Following matrix shows the shortest distances between every pair of vertices:\n"); 30 | for (int i = 0; i < V; i++) { 31 | for (int j = 0; j < V; j++) { 32 | if (dist[i][j] == INF) 33 | printf("%7s", "INF"); 34 | else 35 | printf("%7d", dist[i][j]); 36 | } 37 | printf("\n"); 38 | } 39 | } 40 | 41 | int main() { 42 | int graph[V][V] = { {0, 5, INF, 10}, 43 | {INF, 0, 3, INF}, 44 | {INF, INF, 0, 1}, 45 | {INF, INF, INF, 0} }; 46 | 47 | floydWarshall(graph); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/Go/Floyd-Warshall-Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | const V = 4 9 | const INF = math.MaxInt32 10 | 11 | func floydWarshall(graph [][]int) { 12 | dist := make([][]int, V) 13 | for i := 0; i < V; i++ { 14 | dist[i] = make([]int, V) 15 | copy(dist[i], graph[i]) 16 | } 17 | 18 | for k := 0; k < V; k++ { 19 | for i := 0; i < V; i++ { 20 | for j := 0; j < V; j++ { 21 | if dist[i][k]+dist[k][j] < dist[i][j] { 22 | dist[i][j] = dist[i][k] + dist[k][j] 23 | } 24 | } 25 | } 26 | } 27 | 28 | printSolution(dist) 29 | } 30 | 31 | func printSolution(dist [][]int) { 32 | fmt.Println("Following matrix shows the shortest distances between every pair of vertices:") 33 | for i := 0; i < V; i++ { 34 | for j := 0; j < V; j++ { 35 | if dist[i][j] == INF { 36 | fmt.Printf("INF\t") 37 | } else { 38 | fmt.Printf("%d\t", dist[i][j]) 39 | } 40 | } 41 | fmt.Println() 42 | } 43 | } 44 | 45 | func main() { 46 | graph := [][]int{ 47 | {0, 5, INF, 10}, 48 | {INF, 0, 3, INF}, 49 | {INF, INF, 0, 1}, 50 | {INF, INF, INF, 0}, 51 | } 52 | 53 | floydWarshall(graph) 54 | } 55 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/Java/Floyd-Warshall-Algorithm.java: -------------------------------------------------------------------------------- 1 | public class FloydWarshall { 2 | final static int V = 4; 3 | final static int INF = 99999; 4 | 5 | void floydWarshall(int graph[][]) { 6 | int dist[][] = new int[V][V]; 7 | int i, j, k; 8 | 9 | for (i = 0; i < V; i++) 10 | for (j = 0; j < V; j++) 11 | dist[i][j] = graph[i][j]; 12 | 13 | for (k = 0; k < V; k++) { 14 | for (i = 0; i < V; i++) { 15 | for (j = 0; j < V; j++) { 16 | if (dist[i][k] + dist[k][j] < dist[i][j]) 17 | dist[i][j] = dist[i][k] + dist[k][j]; 18 | } 19 | } 20 | } 21 | 22 | printSolution(dist); 23 | } 24 | 25 | void printSolution(int dist[][]) { 26 | System.out.println("Following matrix shows the shortest distances between every pair of vertices:"); 27 | for (int i = 0; i < V; ++i) { 28 | for (int j = 0; j < V; ++j) { 29 | if (dist[i][j] == INF) 30 | System.out.print("INF "); 31 | else 32 | System.out.print(dist[i][j] + " "); 33 | } 34 | System.out.println(); 35 | } 36 | } 37 | 38 | public static void main(String[] args) { 39 | int graph[][] = { 40 | {0, 5, INF, 10}, 41 | {INF, 0, 3, INF}, 42 | {INF, INF, 0, 1}, 43 | {INF, INF, INF, 0} 44 | }; 45 | FloydWarshall a = new FloydWarshall(); 46 | 47 | a.floydWarshall(graph); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/JavaScript/Floyd-Warshall-Algorithm.js: -------------------------------------------------------------------------------- 1 | const V = 4; 2 | const INF = 99999; 3 | 4 | function floydWarshall(graph) { 5 | const dist = []; 6 | for (let i = 0; i < V; i++) { 7 | dist[i] = graph[i].slice(); 8 | } 9 | 10 | for (let k = 0; k < V; k++) { 11 | for (let i = 0; i < V; i++) { 12 | for (let j = 0; j < V; j++) { 13 | if (dist[i][k] + dist[k][j] < dist[i][j]) { 14 | dist[i][j] = dist[i][k] + dist[k][j]; 15 | } 16 | } 17 | } 18 | } 19 | 20 | printSolution(dist); 21 | } 22 | 23 | function printSolution(dist) { 24 | console.log('Following matrix shows the shortest distances between every pair of vertices:'); 25 | for (let i = 0; i < V; i++) { 26 | for (let j = 0; j < V; j++) { 27 | if (dist[i][j] === INF) { 28 | process.stdout.write('INF\t'); 29 | } else { 30 | process.stdout.write(`${dist[i][j]}\t`); 31 | } 32 | } 33 | console.log(); 34 | } 35 | } 36 | 37 | const graph = [ 38 | [0, 5, INF, 10], 39 | [INF, 0, 3, INF], 40 | [INF, INF, 0, 1], 41 | [INF, INF, INF, 0] 42 | ]; 43 | 44 | floydWarshall(graph); 45 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/Python/Floyd-Warshall-Algorithm.py: -------------------------------------------------------------------------------- 1 | V = 4 2 | INF = 99999 3 | 4 | def floyd_warshall(graph): 5 | dist = [[graph[i][j] for j in range(V)] for i in range(V)] 6 | 7 | for k in range(V): 8 | for i in range(V): 9 | for j in range(V): 10 | if dist[i][k] + dist[k][j] < dist[i][j]: 11 | dist[i][j] = dist[i][k] + dist[k][j] 12 | 13 | print_solution(dist) 14 | 15 | def print_solution(dist): 16 | print("Following matrix shows the shortest distances between every pair of vertices:") 17 | for i in range(V): 18 | for j in range(V): 19 | if dist[i][j] == INF: 20 | print("INF", end=" ") 21 | else: 22 | print(dist[i][j], end=" ") 23 | print() 24 | 25 | graph = [ 26 | [0, 5, INF, 10], 27 | [INF, 0, 3, INF], 28 | [INF, INF, 0, 1], 29 | [INF, INF, INF, 0] 30 | ] 31 | 32 | floyd_warshall(graph) 33 | -------------------------------------------------------------------------------- /Floyd Warshall Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Floyd-Warshall Algorithm 2 | 3 | The Floyd-Warshall algorithm is a dynamic programming algorithm that finds the shortest path between all pairs of vertices in a weighted, directed graph. It can handle negative edge weights but not negative weight cycles. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V^3) 8 | Average: O(V^3) 9 | Worst: O(V^3) 10 | 11 | ## Space Complexity 12 | 13 | O(V^2) 14 | 15 | ## Example Use Case 16 | 17 | Finding the shortest paths between all pairs of vertices in a graph, such as determining the shortest driving times between all pairs of cities or the minimum communication latency between all pairs of computers in a network. 18 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/C++/Heap-Sort-Algortihm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int &a, int &b) { 5 | int temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | 10 | void heapify(int arr[], int n, int i) { 11 | int largest = i; 12 | int left = 2 * i + 1; 13 | int right = 2 * i + 2; 14 | 15 | if (left < n && arr[left] > arr[largest]) 16 | largest = left; 17 | 18 | if (right < n && arr[right] > arr[largest]) 19 | largest = right; 20 | 21 | if (largest != i) { 22 | swap(arr[i], arr[largest]); 23 | heapify(arr, n, largest); 24 | } 25 | } 26 | 27 | void heapSort(int arr[], int n) { 28 | for (int i = n / 2 - 1; i >= 0; i--) 29 | heapify(arr, n, i); 30 | 31 | for (int i = n - 1; i > 0; i--) { 32 | swap(arr[0], arr[i]); 33 | heapify(arr, i, 0); 34 | } 35 | } 36 | 37 | int main() { 38 | int arr[] = {12, 11, 13, 5, 6, 7}; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | heapSort(arr, n); 42 | 43 | for (int i = 0; i < n; ++i) 44 | cout << arr[i] << " "; 45 | cout << endl; 46 | 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/C/Heap-Sort-Algortihm.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *a, int *b) { 4 | int temp = *a; 5 | *a = *b; 6 | *b = temp; 7 | } 8 | 9 | void heapify(int arr[], int n, int i) { 10 | int largest = i; 11 | int left = 2 * i + 1; 12 | int right = 2 * i + 2; 13 | 14 | if (left < n && arr[left] > arr[largest]) 15 | largest = left; 16 | 17 | if (right < n && arr[right] > arr[largest]) 18 | largest = right; 19 | 20 | if (largest != i) { 21 | swap(&arr[i], &arr[largest]); 22 | heapify(arr, n, largest); 23 | } 24 | } 25 | 26 | void heapSort(int arr[], int n) { 27 | for (int i = n / 2 - 1; i >= 0; i--) 28 | heapify(arr, n, i); 29 | 30 | for (int i = n - 1; i > 0; i--) { 31 | swap(&arr[0], &arr[i]); 32 | heapify(arr, i, 0); 33 | } 34 | } 35 | 36 | int main() { 37 | int arr[] = {12, 11, 13, 5, 6, 7}; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | 40 | heapSort(arr, n); 41 | 42 | for (int i = 0; i < n; ++i) 43 | printf("%d ", arr[i]); 44 | printf("\n"); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/Go/Heap-Sort-Algortihm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func swap(a *int, b *int) { 6 | tmp := *a 7 | *a = *b 8 | *b = tmp 9 | } 10 | 11 | func heapify(arr []int, n int, i int) { 12 | largest := i 13 | left := 2*i + 1 14 | right := 2*i + 2 15 | 16 | if left < n && arr[left] > arr[largest] { 17 | largest = left 18 | } 19 | 20 | if right < n && arr[right] > arr[largest] { 21 | largest = right 22 | } 23 | 24 | if largest != i { 25 | swap(&arr[i], &arr[largest]) 26 | heapify(arr, n, largest) 27 | } 28 | } 29 | 30 | func heapSort(arr []int) { 31 | n := len(arr) 32 | 33 | for i := n/2 - 1; i >= 0; i-- { 34 | heapify(arr, n, i) 35 | } 36 | 37 | for i := n - 1; i > 0; i-- { 38 | swap(&arr[0], &arr[i]) 39 | heapify(arr, i, 0) 40 | } 41 | } 42 | 43 | func main() { 44 | arr := []int{12, 11, 13, 5, 6, 7} 45 | 46 | heapSort(arr) 47 | 48 | for _, val := range arr { 49 | fmt.Print(val, " ") 50 | } 51 | fmt.Println() 52 | } 53 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/Java/Heap-Sort-Algortihm.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | public void swap(int[] arr, int a, int b) { 3 | int temp = arr[a]; 4 | arr[a] = arr[b]; 5 | arr[b] = temp; 6 | } 7 | 8 | public void heapify(int[] arr, int n, int i) { 9 | int largest = i; 10 | int left = 2 * i + 1; 11 | int right = 2 * i + 2; 12 | 13 | if (left < n && arr[left] > arr[largest]) { 14 | largest = left; 15 | } 16 | 17 | if (right < n && arr[right] > arr[largest]) { 18 | largest = right; 19 | } 20 | 21 | if (largest != i) { 22 | swap(arr, i, largest); 23 | heapify(arr, n, largest); 24 | } 25 | } 26 | 27 | public void heapSort(int[] arr) { 28 | int n = arr.length; 29 | 30 | for (int i = n / 2 - 1; i >= 0; i--) { 31 | heapify(arr, n, i); 32 | } 33 | 34 | for (int i = n - 1; i > 0; i--) { 35 | swap(arr, 0, i); 36 | heapify(arr, i, 0); 37 | } 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] arr = {12, 11, 13, 5, 6, 7}; 42 | HeapSort heapSort = new HeapSort(); 43 | heapSort.heapSort(arr); 44 | 45 | for (int i : arr) { 46 | System.out.print(i + " "); 47 | } 48 | System.out.println(); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/JavaScript/Heap-Sort-Algortihm.js: -------------------------------------------------------------------------------- 1 | function swap(arr, a, b) { 2 | const temp = arr[a]; 3 | arr[a] = arr[b]; 4 | arr[b] = temp; 5 | } 6 | 7 | function heapify(arr, n, i) { 8 | let largest = i; 9 | const left = 2 * i + 1; 10 | const right = 2 * i + 2; 11 | 12 | if (left < n && arr[left] > arr[largest]) { 13 | largest = left; 14 | } 15 | 16 | if (right < n && arr[right] > arr[largest]) { 17 | largest = right; 18 | } 19 | 20 | if (largest !== i) { 21 | swap(arr, i, largest); 22 | heapify(arr, n, largest); 23 | } 24 | } 25 | 26 | function heapSort(arr) { 27 | const n = arr.length; 28 | 29 | for (let i = n / 2 - 1; i >= 0; i--) { 30 | heapify(arr, n, i); 31 | } 32 | 33 | for (let i = n - 1; i > 0; i--) { 34 | swap(arr, 0, i); 35 | heapify(arr, i, 0); 36 | } 37 | } 38 | 39 | const arr = [12, 11, 13, 5, 6, 7]; 40 | heapSort(arr); 41 | console.log(arr.join(' ')); 42 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/Python/Heap-Sort-Algortihm.py: -------------------------------------------------------------------------------- 1 | def swap(arr, a, b): 2 | arr[a], arr[b] = arr[b], arr[a] 3 | 4 | def heapify(arr, n, i): 5 | largest = i 6 | left = 2 * i + 1 7 | right = 2 * i + 2 8 | 9 | if left < n and arr[i] < arr[left]: 10 | largest = left 11 | 12 | if right < n and arr[largest] < arr[right]: 13 | largest = right 14 | 15 | if largest != i: 16 | swap(arr, i, largest) 17 | heapify(arr, n, largest) 18 | 19 | def heapSort(arr): 20 | n = len(arr) 21 | 22 | for i in range(n, -1, -1): 23 | heapify(arr, n, i) 24 | 25 | for i in range(n-1, 0, -1): 26 | swap(arr, i, 0) 27 | heapify(arr, i, 0) 28 | 29 | arr = [12, 11, 13, 5, 6, 7] 30 | heapSort(arr) 31 | print(" ".join(map(str, arr))) 32 | -------------------------------------------------------------------------------- /Heap Sort Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Heap Sort Algorithm 2 | 3 | Heap Sort is a comparison-based sorting algorithm that works by building a binary heap (either max-heap or min-heap) from the input array and then repeatedly extracting the maximum or minimum element and inserting it at the end of the sorted region. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n _ log(n)) 8 | Average: O(n _ log(n)) 9 | Worst: O(n \* log(n)) 10 | 11 | ## Space Complexity 12 | 13 | O(1) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a large dataset when the available memory is limited, as Heap Sort is an in-place sorting algorithm with a good average and worst-case performance. 18 | -------------------------------------------------------------------------------- /Huffman Coding Compression Algorithm/C++/Huffman Coding: -------------------------------------------------------------------------------- 1 | 2 | class Solution{ 3 | public: 4 | struct Node { 5 | int data; 6 | struct Node* left; 7 | struct Node* right; 8 | 9 | 10 | Node(int val) 11 | { 12 | data = val; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | struct cmp { 19 | 20 | bool operator()(Node* l, Node* r) 21 | 22 | { 23 | return (l->data > r->data); 24 | } 25 | }; 26 | 27 | void preOrder(Node *root,string s,vector&ans){ 28 | if(!root){ 29 | return; 30 | } 31 | 32 | if(!root->left && !root->right){ 33 | ans.push_back(s); 34 | } 35 | 36 | preOrder(root->left,s+"0",ans); 37 | preOrder(root->right,s+"1",ans); 38 | } 39 | 40 | vector huffmanCodes(string S,vector f,int n) 41 | { 42 | priority_queue,cmp> mh; 43 | 44 | for(int i=0; idata + right->data); 55 | parent->left = left; 56 | parent->right = right; 57 | mh.push(parent); 58 | } 59 | 60 | Node *root = mh.top(); 61 | mh.pop(); 62 | vector ans; 63 | preOrder(root,"",ans); 64 | return ans; 65 | 66 | } 67 | }; 68 | -------------------------------------------------------------------------------- /Huffman Coding Compression Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Huffman Coding Compression Algorithm 2 | 3 | Huffman Coding is a lossless data compression algorithm that works by assigning variable-length codes to input characters based on their frequencies. Characters with higher frequencies are assigned shorter codes, while characters with lower frequencies are assigned longer codes. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n + k _ log(k)) 8 | Average: O(n + k _ log(k)) 9 | Worst: O(n + k \* log(k)) 10 | 11 | ## Space Complexity 12 | 13 | O(k) 14 | 15 | ## Example Use Case 16 | 17 | Compressing text data, such as documents or web pages, to reduce storage space or transmission time. 18 | -------------------------------------------------------------------------------- /Insertion Sort Algortihm/Java/Insertion_sort.java: -------------------------------------------------------------------------------- 1 | class InsertionSort { 2 | void sort(int arr[]) { 3 | int n = arr.length; 4 | for (int i = 1; i < n; ++i) { 5 | int key = arr[i]; 6 | int j = i - 1; 7 | while (j >= 0 && arr[j] > key) { 8 | arr[j + 1] = arr[j]; 9 | j = j - 1; 10 | } 11 | arr[j + 1] = key; 12 | } 13 | } 14 | 15 | public static void main(String args[]) { 16 | int[] arr = {12, 11, 13, 5, 6}; 17 | InsertionSort ob = new InsertionSort(); 18 | ob.sort(arr); 19 | printArray(arr); 20 | } 21 | 22 | static void printArray(int arr[]) { 23 | int n = arr.length; 24 | for (int i = 0; i < n; ++i) 25 | System.out.print(arr[i] + " "); 26 | System.out.println(); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Insertion Sort Algortihm/Python/Insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(arr): 2 | n = len(arr) 3 | 4 | if n <= 1: 5 | return 6 | 7 | for i in range(1, n): 8 | pointer = arr[i] 9 | j = i-1 10 | while j >= 0 and pointer < arr[j]: 11 | arr[j+1] = arr[j] 12 | j -= 1 13 | arr[j+1] = pointer 14 | 15 | 16 | arr = [12, 11, 13, 5, 6, 9, 59, 0, 7, 43] 17 | insertion_sort(arr) 18 | print(arr) -------------------------------------------------------------------------------- /Insertion Sort Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Insertion Sort Algorithm 2 | 3 | Insertion Sort is a simple, comparison-based sorting algorithm that builds the final sorted array one element at a time. It is best suited for small or partially sorted datasets. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n) 8 | Average: O(n^2) 9 | Worst: O(n^2) 10 | 11 | ## Space Complexity 12 | 13 | O(1) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a small dataset or sorting an array that is already partially sorted, such as inserting new elements into a sorted list or maintaining the order of elements in a list as they are modified. 18 | -------------------------------------------------------------------------------- /InsertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(arr) { 2 | for (let i = 1; i < arr.length; i++) { 3 | let currentValue = arr[i] 4 | let j 5 | for (j = i - 1; j >= 0 && arr[j] > currentValue; j--) { 6 | arr[j + 1] = arr[j] 7 | } 8 | arr[j + 1] = currentValue 9 | } 10 | return arr 11 | } 12 | console.log(insertionSort([2, 1, 3, 7, 5])) // [1, 2, 3, 5, 7] 13 | -------------------------------------------------------------------------------- /Insertion_sort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(arr): 2 | n = len(arr) 3 | 4 | if n <= 1: 5 | return 6 | 7 | for i in range(1, n): 8 | pointer = arr[i] 9 | j = i-1 10 | while j >= 0 and pointer < arr[j]: 11 | arr[j+1] = arr[j] 12 | j -= 1 13 | arr[j+1] = pointer 14 | 15 | 16 | arr = [12, 11, 13, 5, 6, 9, 59, 0, 7, 43] 17 | insertion_sort(arr) 18 | print(arr) -------------------------------------------------------------------------------- /KMP Algortihm/C++/KMP algorithm: -------------------------------------------------------------------------------- 1 | // Pattern Matching Algorithm by using KMP Algorithm 2 | 3 | class Solution { 4 | public: 5 | 6 | vector fillLPS(string str){ 7 | int n = str.size(); 8 | vectorlps(n,0); 9 | int len =0, i = 1; 10 | lps[0]=0; 11 | while(ilps = fillLPS(needle); 32 | int i=0, j=0; 33 | while(i a[2] - b[2]); 14 | 15 | let parent = Array(this.V).fill(-1); 16 | 17 | function find(parent, i) { 18 | if (parent[i] === -1) return i; 19 | return find(parent, parent[i]); 20 | } 21 | 22 | function union(parent, x, y) { 23 | let xSet = find(parent, x); 24 | let ySet = find(parent, y); 25 | parent[xSet] = ySet; 26 | } 27 | 28 | let result = []; 29 | let e = 0; 30 | let i = 0; 31 | 32 | while (e < this.V - 1) { 33 | let [u, v, w] = this.graph[i]; 34 | i++; 35 | 36 | let x = find(parent, u); 37 | let y = find(parent, v); 38 | 39 | if (x !== y) { 40 | result.push([u, v, w]); 41 | e++; 42 | union(parent, x, y); 43 | } 44 | } 45 | 46 | return result; 47 | } 48 | } 49 | 50 | // Example usage: 51 | const vertices = 4; 52 | const graph = new Graph(vertices); 53 | 54 | graph.addEdge(0, 1, 10); 55 | graph.addEdge(0, 2, 6); 56 | graph.addEdge(0, 3, 5); 57 | graph.addEdge(1, 3, 15); 58 | graph.addEdge(2, 3, 4); 59 | 60 | const minimumSpanningTree = graph.kruskalMST(); 61 | console.log("Minimum Spanning Tree:"); 62 | console.log(minimumSpanningTree); 63 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/Kruskal's Algorithm(Python).py: -------------------------------------------------------------------------------- 1 | # Kruskal's algorithm to find MST based on Union-Find implemented in Python 2 | 3 | import sys 4 | 5 | # Create a class to represent a graph 6 | class Graph: 7 | def __init__(self, n) -> None: 8 | self.n = n 9 | self.graph = [] 10 | 11 | # add edge to graph 12 | def add_edge(self, v1, v2, cost) -> None: 13 | self.graph.append([v1,v2,cost]) 14 | 15 | def is_valid(self) -> bool: 16 | vert_set = set(list(range(self.n))) 17 | graph_set = set() 18 | for [v1, v2, c] in self.graph: 19 | graph_set.add(v1) 20 | graph_set.add(v2) 21 | if vert_set == graph_set: 22 | return True 23 | else: 24 | return False 25 | 26 | 27 | # find set of node v 28 | def find(self, parents, v) -> int: 29 | if parents[v] == v: 30 | return v 31 | return self.find(parents, parents[v]) 32 | 33 | # does union of 2 sets of nodes v1 and v2 by rank 34 | def union(self, parents, rank, v1, v2): 35 | v1r = self.find(parents, v1) 36 | v2r = self.find(parents, v2) 37 | if rank[v1r] == rank[v2r]: 38 | parents[v2r] = v1r 39 | rank[v1r] += 1 40 | elif rank[v1r] > rank[v2r]: 41 | parents[v2r] = v1r 42 | else: 43 | parents[v1r] = v2r 44 | 45 | # constructs MST using Kruskal's Algorithm 46 | def kruskals(self) -> list: 47 | MST = [] 48 | 49 | # order edges by cost 50 | ordered_edges = sorted(self.graph, key=lambda x: x[2]) 51 | 52 | parents = [] 53 | rank = [] 54 | # intialize sets for all of the nodes 55 | for node in range(self.n): 56 | parents.append(node) 57 | rank.append(0) 58 | 59 | nodes = 0 60 | i = 0 61 | # run loop until all nodes have been encountered by MST 62 | while nodes < self.n - 1: 63 | v1, v2, cost = ordered_edges[i] 64 | i = i + 1 65 | v1r = self.find(parents, v1) 66 | v2r = self.find(parents, v2) 67 | # check if v1 and v2 are in different clusters (no cycle creation) 68 | if v1r != v2r: 69 | nodes = nodes + 1 70 | MST.append([v1, v2, cost]) 71 | # combine the sets of v1 and v2 using union-rank 72 | self.union(parents, rank, v1r, v2r) 73 | return MST 74 | 75 | def main(): 76 | n = int(input("Enter the number of vertices for the graph as an integer): ")) 77 | g = Graph(n) 78 | 79 | print("Now begin entering edges as prompted.") 80 | print("The edge should be formatted as 3 numbers (index of v1 and index of v2 and the cost) separated by one space in between.") 81 | print("EXAMPLE: edge connecting vertices 4 and 6 with cost 13.2 should be entered like this: 4 6 13.2") 82 | print("Type quit if there are no more edges") 83 | e_s = input("Enter edge: ") 84 | while e_s != "quit": 85 | e_l = e_s.split(" ") 86 | v1 = int(e_l[0]) 87 | v2 = int(e_l[1]) 88 | cost = float(e_l[2]) 89 | g.add_edge(v1, v2, cost) 90 | e_s = input("Enter edge: ") 91 | if not g.is_valid(): 92 | print("The edges entered do not consitute a connected graph of " + str(g.n) + " vertices") 93 | else: 94 | MST = g.kruskals() 95 | print("Here is a list representation of the edges that make up the MST of the input graph") 96 | print(MST) 97 | 98 | main() 99 | 100 | # Example Test Case 1 101 | # Graph 102 | # g = Graph(6) 103 | # g.add_edge(0, 1, 4) 104 | # g.add_edge(0, 2, 4) 105 | # g.add_edge(1, 2, 2) 106 | # g.add_edge(1, 0, 4) 107 | # g.add_edge(2, 0, 4) 108 | # g.add_edge(2, 1, 2) 109 | # g.add_edge(2, 3, 3) 110 | # g.add_edge(2, 5, 2) 111 | # g.add_edge(2, 4, 4) 112 | # g.add_edge(3, 2, 3) 113 | # g.add_edge(3, 4, 3) 114 | # g.add_edge(4, 2, 4) 115 | # g.add_edge(4, 3, 3) 116 | # g.add_edge(5, 2, 2) 117 | # g.add_edge(5, 4, 3) 118 | 119 | #MST 120 | # [[1, 2, 2], [2, 5, 2], [2, 3, 3], [3, 4, 3], [0, 1, 4]] 121 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/Kruskal's Algorithm(in C).c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Structure to represent an edge in the graph 5 | struct Edge { 6 | int src, dest, weight; 7 | }; 8 | 9 | // Structure to represent a graph 10 | struct Graph { 11 | int V, E; // Number of vertices and edges 12 | struct Edge* edge; 13 | }; 14 | 15 | // Create a graph with V vertices and E edges 16 | struct Graph* createGraph(int V, int E) { 17 | struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph)); 18 | graph->V = V; 19 | graph->E = E; 20 | graph->edge = (struct Edge*)malloc(E * sizeof(struct Edge)); 21 | return graph; 22 | } 23 | 24 | // Compare function used to sort edges based on their weights 25 | int compare(const void* a, const void* b) { 26 | return ((struct Edge*)a)->weight - ((struct Edge*)b)->weight; 27 | } 28 | 29 | // Find set of an element 'i' 30 | int find(int parent[], int i) { 31 | if (parent[i] == -1) 32 | return i; 33 | return find(parent, parent[i]); 34 | } 35 | 36 | // Union of two sets of x and y 37 | void unionSets(int parent[], int x, int y) { 38 | int xset = find(parent, x); 39 | int yset = find(parent, y); 40 | parent[xset] = yset; 41 | } 42 | 43 | // Kruskal's algorithm to find Minimum Spanning Tree 44 | void kruskalMST(struct Graph* graph) { 45 | int V = graph->V; 46 | struct Edge result[V]; // This will store the resultant MST 47 | int e = 0; // Index variable for result[] 48 | int i = 0; // Index variable for sorted edges 49 | 50 | // Sort all the edges in non-decreasing order of their weight 51 | qsort(graph->edge, graph->E, sizeof(graph->edge[0]), compare); 52 | 53 | int* parent = (int*)malloc(V * sizeof(int)); 54 | // Initialize all subsets as single element sets 55 | for (int v = 0; v < V; v++) { 56 | parent[v] = -1; 57 | } 58 | 59 | // Number of edges to be taken is equal to V-1 60 | while (e < V - 1) { 61 | struct Edge nextEdge = graph->edge[i++]; 62 | int x = find(parent, nextEdge.src); 63 | int y = find(parent, nextEdge.dest); 64 | 65 | // If including this edge doesn't cause a cycle, include it 66 | if (x != y) { 67 | result[e++] = nextEdge; 68 | unionSets(parent, x, y); 69 | } 70 | } 71 | 72 | // Print the edges of MST 73 | printf("Edges of Minimum Spanning Tree:\n"); 74 | for (i = 0; i < e; i++) { 75 | printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].weight); 76 | } 77 | 78 | free(parent); 79 | } 80 | 81 | int main() { 82 | int V = 4; // Number of vertices 83 | int E = 5; // Number of edges 84 | struct Graph* graph = createGraph(V, E); 85 | 86 | // Add edge 0-1 87 | graph->edge[0].src = 0; 88 | graph->edge[0].dest = 1; 89 | graph->edge[0].weight = 10; 90 | 91 | // Add edge 0-2 92 | graph->edge[1].src = 0; 93 | graph->edge[1].dest = 2; 94 | graph->edge[1].weight = 6; 95 | 96 | // Add edge 0-3 97 | graph->edge[2].src = 0; 98 | graph->edge[2].dest = 3; 99 | graph->edge[2].weight = 5; 100 | 101 | // Add edge 1-3 102 | graph->edge[3].src = 1; 103 | graph->edge[3].dest = 3; 104 | graph->edge[3].weight = 15; 105 | 106 | // Add edge 2-3 107 | graph->edge[4].src = 2; 108 | graph->edge[4].dest = 3; 109 | graph->edge[4].weight = 4; 110 | 111 | kruskalMST(graph); 112 | 113 | return 0; 114 | } 115 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/Kruskal's Algorithm(in C++).cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | // Structure to represent an edge in the graph 8 | struct Edge { 9 | int src, dest, weight; 10 | }; 11 | 12 | // Structure to represent a graph 13 | class Graph { 14 | public: 15 | int V, E; // Number of vertices and edges 16 | vector edge; // Vector to store edges 17 | 18 | // Constructor 19 | Graph(int v, int e) { 20 | V = v; 21 | E = e; 22 | edge.resize(E); 23 | } 24 | 25 | // Function to add an edge to the graph 26 | void addEdge(int src, int dest, int weight) { 27 | edge.push_back({src, dest, weight}); 28 | } 29 | 30 | // Function to find the parent of a vertex 31 | int findParent(int parent[], int i) { 32 | if (parent[i] == -1) 33 | return i; 34 | return findParent(parent, parent[i]); 35 | } 36 | 37 | // Function to perform union of two sets 38 | void unionSets(int parent[], int x, int y) { 39 | int xset = findParent(parent, x); 40 | int yset = findParent(parent, y); 41 | parent[xset] = yset; 42 | } 43 | 44 | // Function to run Kruskal's algorithm and find the minimum spanning tree 45 | void kruskalMST() { 46 | vector result; // Vector to store the resultant MST 47 | 48 | // Sort all the edges in non-decreasing order of their weight 49 | sort(edge.begin(), edge.end(), [](const Edge& a, const Edge& b) { 50 | return a.weight < b.weight; 51 | }); 52 | 53 | int* parent = new int[V]; 54 | fill(parent, parent + V, -1); 55 | 56 | for (Edge currentEdge : edge) { 57 | int x = findParent(parent, currentEdge.src); 58 | int y = findParent(parent, currentEdge.dest); 59 | 60 | // If including this edge doesn't create a cycle, add it to the MST 61 | if (x != y) { 62 | result.push_back(currentEdge); 63 | unionSets(parent, x, y); 64 | } 65 | } 66 | 67 | // Print the edges of the MST 68 | cout << "Edges of Minimum Spanning Tree:" << endl; 69 | for (Edge edge : result) { 70 | cout << edge.src << " -- " << edge.dest << " == " << edge.weight << endl; 71 | } 72 | 73 | delete[] parent; 74 | } 75 | }; 76 | 77 | int main() { 78 | int V = 4; // Number of vertices 79 | int E = 5; // Number of edges 80 | Graph graph(V, E); 81 | 82 | // Add edges to the graph 83 | graph.addEdge(0, 1, 10); 84 | graph.addEdge(0, 2, 6); 85 | graph.addEdge(0, 3, 5); 86 | graph.addEdge(1, 3, 15); 87 | graph.addEdge(2, 3, 4); 88 | 89 | // Find and print the Minimum Spanning Tree using Kruskal's algorithm 90 | graph.kruskalMST(); 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/Kruskal's Algorithm.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "sort" 6 | ) 7 | 8 | type Edge struct { 9 | src, dest, weight int 10 | } 11 | 12 | type Graph struct { 13 | vertices, edges int 14 | edgeList []Edge 15 | } 16 | 17 | func (g *Graph) addEdge(src, dest, weight int) { 18 | g.edgeList = append(g.edgeList, Edge{src, dest, weight}) 19 | } 20 | 21 | func (g *Graph) kruskalMST() []Edge { 22 | // Sort the edges by weight in ascending order 23 | sort.Slice(g.edgeList, func(i, j int) bool { 24 | return g.edgeList[i].weight < g.edgeList[j].weight 25 | }) 26 | 27 | parent := make([]int, g.vertices) 28 | for i := 0; i < g.vertices; i++ { 29 | parent[i] = i 30 | } 31 | 32 | var result []Edge 33 | for _, edge := range g.edgeList { 34 | srcParent := g.find(parent, edge.src) 35 | destParent := g.find(parent, edge.dest) 36 | 37 | if srcParent != destParent { 38 | result = append(result, edge) 39 | parent[srcParent] = destParent 40 | } 41 | } 42 | 43 | return result 44 | } 45 | 46 | func (g *Graph) find(parent []int, vertex int) int { 47 | if parent[vertex] != vertex { 48 | return g.find(parent, parent[vertex]) 49 | } 50 | return vertex 51 | } 52 | 53 | func main() { 54 | g := Graph{ 55 | vertices: 4, 56 | edges: 5, 57 | } 58 | g.addEdge(0, 1, 10) 59 | g.addEdge(0, 2, 6) 60 | g.addEdge(0, 3, 5) 61 | g.addEdge(1, 3, 15) 62 | g.addEdge(2, 3, 4) 63 | 64 | mst := g.kruskalMST() 65 | 66 | fmt.Println("Edges in Minimum Spanning Tree:") 67 | for _, edge := range mst { 68 | fmt.Printf("Edge: %d - %d, Weight: %d\n", edge.src, edge.dest, edge.weight) 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Kruskal's Algorithm 2 | 3 | Kruskal's Algorithm is a greedy algorithm that finds the minimum spanning tree for a connected, undirected graph with weighted edges. It works by repeatedly selecting the edge with the lowest weight that does not form a cycle. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(E _ log(E)) 8 | Average: O(E _ log(E)) 9 | Worst: O(E \* log(E)) 10 | 11 | ## Space Complexity 12 | 13 | O(V + E) 14 | 15 | ## Example Use Case 16 | 17 | Finding the minimum spanning tree in a connected graph, such as designing a network with minimal wiring cost or determining the optimal route for connecting a set of cities with roads. 18 | -------------------------------------------------------------------------------- /Kruskal's Algorithm/kruskal.java: -------------------------------------------------------------------------------- 1 | import Java.util.*; 2 | 3 | class KruskalAlgorithm { 4 | 5 | class Edge implements Comparable { 6 | int source, destination, weight; 7 | 8 | public int compareTo(Edge edgeToCompare) { 9 | return this.weight - edgeToCompare.weight; 10 | } 11 | }; 12 | 13 | 14 | class Subset { 15 | int parent, value; 16 | }; 17 | 18 | 19 | int vertices, edges; 20 | Edge edgeArray[]; 21 | 22 | 23 | KruskalAlgorithm(int vertices, int edges) { 24 | this.vertices = vertices; 25 | this.edges = edges; 26 | edgeArray = new Edge[this.edges]; 27 | for (int i = 0; i < edges; ++i) 28 | edgeArray[i] = new Edge(); 29 | } 30 | 31 | 32 | void applyKruskal() { 33 | 34 | 35 | Edge finalResult[] = new Edge[vertices]; 36 | int newEdge = 0; 37 | int index = 0; 38 | for (index = 0; index < vertices; ++index) 39 | finalResult[index] = new Edge(); 40 | 41 | 42 | Arrays.sort(edgeArray); 43 | 44 | 45 | Subset subsetArray[] = new Subset[vertices]; 46 | 47 | 48 | for (index = 0; index < vertices; ++index) 49 | subsetArray[index] = new Subset(); 50 | 51 | 52 | for (int vertex = 0; vertex < vertices; ++vertex) { 53 | subsetArray[vertex].parent = vertex; 54 | subsetArray[vertex].value = 0; 55 | } 56 | index = 0; 57 | 58 | 59 | while (newEdge < vertices - 1) { 60 | 61 | Edge nextEdge = new Edge(); 62 | nextEdge = edgeArray[index++]; 63 | 64 | int nextSource = findSetOfElement(subsetArray, nextEdge.source); 65 | int nextDestination = findSetOfElement(subsetArray, nextEdge.destination); 66 | 67 | 68 | if (nextSource != nextDestination) { 69 | finalResult[newEdge++] = nextEdge; 70 | performUnion(subsetArray, nextSource, nextDestination); 71 | } 72 | } 73 | for (index = 0; index < newEdge; ++index) 74 | System.out.println(finalResult[index].source + " - " + finalResult[index].destination + ": " + finalResult[index].weight); 75 | } 76 | 77 | 78 | int findSetOfElement(Subset subsetArray[], int i) { 79 | if (subsetArray[i].parent != i) 80 | subsetArray[i].parent = findSetOfElement(subsetArray, subsetArray[i].parent); 81 | return subsetArray[i].parent; 82 | } 83 | 84 | 85 | void performUnion(Subset subsetArray[], int sourceRoot, int destinationRoot) { 86 | 87 | int nextSourceRoot = findSetOfElement(subsetArray, sourceRoot); 88 | int nextDestinationRoot = findSetOfElement(subsetArray, destinationRoot); 89 | 90 | if (subsetArray[nextSourceRoot].value < subsetArray[nextDestinationRoot].value) 91 | subsetArray[nextSourceRoot].parent = nextDestinationRoot; 92 | else if (subsetArray[nextSourceRoot].value > subsetArray[nextDestinationRoot].value) 93 | subsetArray[nextDestinationRoot].parent = nextSourceRoot; 94 | else { 95 | subsetArray[nextDestinationRoot].parent = nextSourceRoot; 96 | subsetArray[nextSourceRoot].value++; 97 | } 98 | } 99 | 100 | 101 | public static void main(String[] args) { 102 | 103 | int v, e; 104 | 105 | Scanner sc = new Scanner(System.in); 106 | 107 | 108 | System.out.println("Enter number of vertices: "); 109 | 110 | 111 | v = sc.nextInt(); 112 | 113 | 114 | System.out.println("Enter number of edges"); 115 | 116 | 117 | e = sc.nextInt(); 118 | 119 | KruskalAlgorithm graph = new KruskalAlgorithm(v, e); 120 | 121 | for(int i = 0; i < e; i++){ 122 | System.out.println("Enter source value for edge["+ i +"]"); 123 | graph.edgeArray[i].source = sc.nextInt(); 124 | 125 | System.out.println("Enter destination value for edge["+ i +"]"); 126 | graph.edgeArray[i].destination = sc.nextInt(); 127 | 128 | System.out.println("Enter weight for edge["+i+"]"); 129 | graph.edgeArray[i].weight = sc.nextInt(); 130 | } 131 | 132 | 133 | graph.applyKruskal(); 134 | } 135 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Abhay Singh Rathore 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Lee Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Lee Algorithm 2 | 3 | The Lee Algorithm is a pathfinding algorithm that finds the shortest path between two points in a grid, considering obstacles. It uses Breadth-First Search (BFS) to explore the grid, and it can handle diagonal moves as well. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n^2) 8 | Average: O(n^2) 9 | Worst: O(n^2) 10 | 11 | ## Space Complexity 12 | 13 | O(n^2) 14 | 15 | ## Example Use Case 16 | 17 | Finding the shortest path between two points in a grid with obstacles, such as routing a wire on a circuit board or navigating a robot through a maze. 18 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/C++/Merge Sort: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 5 | // Merges two subarrays of array[]. 6 | // First subarray is arr[begin..mid] 7 | // Second subarray is arr[mid+1..end] 8 | void merge(int array[], int const left, int const mid, 9 | int const right) 10 | { 11 | int const subArrayOne = mid - left + 1; 12 | int const subArrayTwo = right - mid; 13 | 14 | // Create temp arrays 15 | auto *leftArray = new int[subArrayOne], 16 | *rightArray = new int[subArrayTwo]; 17 | 18 | // Copy data to temp arrays leftArray[] and rightArray[] 19 | for (auto i = 0; i < subArrayOne; i++) 20 | leftArray[i] = array[left + i]; 21 | for (auto j = 0; j < subArrayTwo; j++) 22 | rightArray[j] = array[mid + 1 + j]; 23 | 24 | auto indexOfSubArrayOne = 0, indexOfSubArrayTwo = 0; 25 | int indexOfMergedArray = left; 26 | 27 | // Merge the temp arrays back into array[left..right] 28 | while (indexOfSubArrayOne < subArrayOne 29 | && indexOfSubArrayTwo < subArrayTwo) { 30 | if (leftArray[indexOfSubArrayOne] 31 | <= rightArray[indexOfSubArrayTwo]) { 32 | array[indexOfMergedArray] 33 | = leftArray[indexOfSubArrayOne]; 34 | indexOfSubArrayOne++; 35 | } 36 | else { 37 | array[indexOfMergedArray] 38 | = rightArray[indexOfSubArrayTwo]; 39 | indexOfSubArrayTwo++; 40 | } 41 | indexOfMergedArray++; 42 | } 43 | 44 | // Copy the remaining elements of 45 | // left[], if there are any 46 | while (indexOfSubArrayOne < subArrayOne) { 47 | array[indexOfMergedArray] 48 | = leftArray[indexOfSubArrayOne]; 49 | indexOfSubArrayOne++; 50 | indexOfMergedArray++; 51 | } 52 | 53 | // Copy the remaining elements of 54 | // right[], if there are any 55 | while (indexOfSubArrayTwo < subArrayTwo) { 56 | array[indexOfMergedArray] 57 | = rightArray[indexOfSubArrayTwo]; 58 | indexOfSubArrayTwo++; 59 | indexOfMergedArray++; 60 | } 61 | delete[] leftArray; 62 | delete[] rightArray; 63 | } 64 | 65 | // begin is for left index and end is right index 66 | // of the sub-array of arr to be sorted 67 | void mergeSort(int array[], int const begin, int const end) 68 | { 69 | if (begin >= end) 70 | return; 71 | 72 | int mid = begin + (end - begin) / 2; 73 | mergeSort(array, begin, mid); 74 | mergeSort(array, mid + 1, end); 75 | merge(array, begin, mid, end); 76 | } 77 | 78 | // UTILITY FUNCTIONS 79 | // Function to print an array 80 | void printArray(int A[], int size) 81 | { 82 | for (int i = 0; i < size; i++) 83 | cout << A[i] << " "; 84 | cout << endl; 85 | } 86 | 87 | // Driver code 88 | int main() 89 | { 90 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 91 | int arr_size = sizeof(arr) / sizeof(arr[0]); 92 | 93 | cout << "Given array is \n"; 94 | printArray(arr, arr_size); 95 | 96 | mergeSort(arr, 0, arr_size - 1); 97 | 98 | cout << "\nSorted array is \n"; 99 | printArray(arr, arr_size); 100 | return 0; 101 | } 102 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/C++/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void conqurer(int *a, int s, int e, int mid) 5 | { 6 | int *merged = new int[e - s + 1]; 7 | int index1 = s; 8 | int index2 = mid + 1; 9 | int mainindex = 0; 10 | 11 | while (index1 <= mid && index2 <= e) 12 | { 13 | if (a[index1] <= a[index2]) 14 | { 15 | merged[mainindex++] = a[index1++]; 16 | } 17 | else 18 | { 19 | merged[mainindex++] = a[index2++]; 20 | } 21 | } 22 | while (index1 <= mid) 23 | { 24 | merged[mainindex++] = a[index1++]; 25 | } 26 | while (index2 <= e) 27 | { 28 | merged[mainindex++] = a[index2++]; 29 | } 30 | 31 | for (int i = 0, j = s; i < (e - s) + 1; i++, j++) 32 | { 33 | a[j] = merged[i]; 34 | } 35 | 36 | delete[] merged; 37 | } 38 | 39 | void divide(int *a, int s, int e) 40 | { 41 | while (s >= e) 42 | { 43 | return; 44 | } 45 | int mid = (s + e) / 2; 46 | divide(a, s, mid); 47 | divide(a, mid + 1, e); 48 | 49 | conqurer(a, s, e, mid); 50 | } 51 | int main() 52 | { 53 | int a[20] = {4, 5, 6, 3, 12}; 54 | int size = 5; 55 | divide(a, 0, size - 1); 56 | for (int i = 0; i < size; i++) 57 | { 58 | cout << a[i] << " "; 59 | } 60 | return 0; 61 | } 62 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/C++/Triway_merge_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Merge three subarrays: [left, mid1), [mid1, mid2), [mid2, right) 6 | * 7 | * @param arr The array to be merged 8 | * @param left The left index of the subarray 9 | * @param mid1 The middle index of the first subarray 10 | * @param mid2 The middle index of the second subarray 11 | * @param right The right index of the subarray 12 | */ 13 | void merge(std::vector &arr, int left, int mid1, int mid2, int right) { 14 | int n1 = mid1 - left; 15 | int n2 = mid2 - mid1; 16 | int n3 = right - mid2; 17 | 18 | std::vector leftArr(n1); 19 | std::vector midArr(n2); 20 | std::vector rightArr(n3); 21 | 22 | // Copy data to temporary arrays 23 | for (int i = 0; i < n1; i++) 24 | leftArr[i] = arr[left + i]; 25 | for (int i = 0; i < n2; i++) 26 | midArr[i] = arr[mid1 + i]; 27 | for (int i = 0; i < n3; i++) 28 | rightArr[i] = arr[mid2 + i]; 29 | 30 | int i = 0, j = 0, k = 0, index = left; 31 | 32 | // Merge the three arrays back into arr 33 | while (i < n1 && j < n2 && k < n3) { 34 | if (leftArr[i] <= midArr[j] && leftArr[i] <= rightArr[k]) { 35 | arr[index++] = leftArr[i++]; 36 | } else if (midArr[j] <= leftArr[i] && midArr[j] <= rightArr[k]) { 37 | arr[index++] = midArr[j++]; 38 | } else { 39 | arr[index++] = rightArr[k++]; 40 | } 41 | } 42 | 43 | // Copy any remaining elements if any 44 | while (i < n1) 45 | arr[index++] = leftArr[i++]; 46 | while (j < n2) 47 | arr[index++] = midArr[j++]; 48 | while (k < n3) 49 | arr[index++] = rightArr[k++]; 50 | } 51 | 52 | /** 53 | * Perform three-way merge sort on an array 54 | * 55 | * @param arr The array to be sorted 56 | * @param left The left index of the subarray 57 | * @param right The right index of the subarray 58 | */ 59 | void mergeSort(std::vector &arr, int left, int right) { 60 | if (right - left > 1) { 61 | int n = right - left; 62 | int mid1 = left + n / 3; 63 | int mid2 = left + 2 * n / 3; 64 | 65 | mergeSort(arr, left, mid1); 66 | mergeSort(arr, mid1, mid2); 67 | mergeSort(arr, mid2, right); 68 | 69 | merge(arr, left, mid1, mid2, right); 70 | } 71 | } 72 | 73 | int main() { 74 | std::vector arr = {12, 11, 13, 5, 6, 7, 10, 21, 9, 8, 1, 11, 13, 21, 10, 19, 6, 7, 10}; 75 | int n = arr.size(); 76 | 77 | std::cout << "Original array: "; 78 | for (int num : arr) 79 | std::cout << num << " "; 80 | std::cout << std::endl; 81 | 82 | mergeSort(arr, 0, n); 83 | 84 | std::cout << "Sorted array: "; 85 | for (int num : arr) 86 | std::cout << num << " "; 87 | std::cout << std::endl; 88 | 89 | return 0; 90 | } 91 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/C/MergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void merge(int arr[], int l, int m, int r) 5 | { 6 | int i, j, k; 7 | int n1 = m - l + 1; 8 | int n2 = r - m; 9 | 10 | int L[n1], R[n2]; 11 | 12 | for (i = 0; i < n1; i++) 13 | L[i] = arr[l + i]; 14 | for (j = 0; j < n2; j++) 15 | R[j] = arr[m + 1 + j]; 16 | 17 | i = 0; 18 | j = 0; 19 | k = l; 20 | 21 | while (i < n1 && j < n2) { 22 | if (L[i] <= R[j]) { 23 | arr[k] = L[i]; 24 | i++; 25 | } 26 | else { 27 | arr[k] = R[j]; 28 | j++; 29 | } 30 | k++; 31 | } 32 | 33 | while (i < n1) { 34 | arr[k] = L[i]; 35 | i++; 36 | k++; 37 | } 38 | 39 | while (j < n2) { 40 | arr[k] = R[j]; 41 | j++; 42 | k++; 43 | } 44 | } 45 | 46 | void mergeSort(int arr[], int l, int r) 47 | { 48 | if (l < r) { 49 | 50 | int m = l + (r - l) / 2; 51 | mergeSort(arr, l, m); 52 | mergeSort(arr, m + 1, r); 53 | 54 | merge(arr, l, m, r); 55 | } 56 | } 57 | 58 | void printArray(int A[], int size) 59 | { 60 | int i; 61 | for (i = 0; i < size; i++) 62 | printf("%d ", A[i]); 63 | printf("\n"); 64 | } 65 | 66 | int main() 67 | { 68 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 69 | int arr_size = sizeof(arr) / sizeof(arr[0]); 70 | 71 | printf("Given array is \n"); 72 | printArray(arr, arr_size); 73 | 74 | mergeSort(arr, 0, arr_size - 1); 75 | 76 | printf("\nSorted array is \n"); 77 | printArray(arr, arr_size); 78 | return 0; 79 | } 80 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/Go/merge_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func mergeSort(arr []int) []int { 6 | if len(arr) <= 1 { 7 | return arr 8 | } 9 | middle := len(arr) / 2 10 | left := mergeSort(arr[:middle]) 11 | right := mergeSort(arr[middle:]) 12 | return merge(left, right) 13 | } 14 | 15 | func merge(left, right []int) []int { 16 | result := make([]int, len(left)+len(right)) 17 | i, j := 0, 0 18 | for k := 0; k < len(result); k++ { 19 | if i >= len(left) { 20 | result[k] = right[j] 21 | j++ 22 | } else if j >= len(right) { 23 | result[k] = left[i] 24 | i++ 25 | } else if left[i] < right[j] { 26 | result[k] = left[i] 27 | i++ 28 | } else { 29 | result[k] = right[j] 30 | j++ 31 | } 32 | } 33 | return result 34 | } 35 | 36 | func main() { 37 | arr := []int{5, 2, 6, 3, 1, 4} 38 | fmt.Println("The given unsorted array is:", arr) 39 | sorted := mergeSort(arr) 40 | fmt.Println("The sorted array is:", sorted) 41 | } -------------------------------------------------------------------------------- /Merge Sort Algorithm/Java/MergeSort.java: -------------------------------------------------------------------------------- 1 | public class MergeSort { 2 | void merge(int arr[], int beg, int mid, int end) { 3 | int l = mid - beg + 1; 4 | int r = end - mid; 5 | int LeftArray[] = new int[l]; 6 | int RightArray[] = new int[r]; 7 | for (int i = 0; i < l; ++i) 8 | LeftArray[i] = arr[beg + i]; 9 | for (int j = 0; j < r; ++j) 10 | RightArray[j] = arr[mid + 1 + j]; 11 | int i = 0, j = 0; 12 | int k = beg; 13 | while (i < l && j < r) { 14 | if (LeftArray[i] <= RightArray[j]) { 15 | arr[k] = LeftArray[i]; 16 | i++; 17 | } else { 18 | arr[k] = RightArray[j]; 19 | j++; 20 | } 21 | k++; 22 | } 23 | while (i < l) { 24 | arr[k] = LeftArray[i]; 25 | i++; 26 | k++; 27 | } 28 | while (j < r) { 29 | arr[k] = RightArray[j]; 30 | j++; 31 | k++; 32 | } 33 | } 34 | 35 | void sort(int arr[], int beg, int end) { 36 | if (beg < end) { 37 | int mid = (beg + end) / 2; 38 | sort(arr, beg, mid); 39 | sort(arr, mid + 1, end); 40 | merge(arr, beg, mid, end); 41 | } 42 | } 43 | 44 | public static void main(String args[]) { 45 | int arr[] = { 40, 51, 22, 45, 1, 4, 90, 23, 17, 55 }; 46 | MergeSort ob = new MergeSort(); 47 | ob.sort(arr, 0, arr.length - 1); 48 | System.out.println("nSorted array"); 49 | for (int i = 0; i < arr.length; i++) { 50 | System.out.println(arr[i] + ""); 51 | } 52 | } 53 | } -------------------------------------------------------------------------------- /Merge Sort Algorithm/Java/MergeSortAlgorithm.java: -------------------------------------------------------------------------------- 1 | // Java program for Merge Sort 2 | 3 | // Driver Class 4 | class MergeSort { 5 | // Merges two subarrays of arr[]. 6 | // First subarray is arr[l..m] 7 | // Second subarray is arr[m+1..r] 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | // Find sizes of two subarrays to be merged 11 | int n1 = m - l + 1; 12 | int n2 = r - m; 13 | 14 | // Create temp arrays 15 | int L[] = new int[n1]; 16 | int R[] = new int[n2]; 17 | 18 | // Copy data to temp arrays 19 | for (int i = 0; i < n1; ++i) 20 | L[i] = arr[l + i]; 21 | for (int j = 0; j < n2; ++j) 22 | R[j] = arr[m + 1 + j]; 23 | 24 | // Merge the temp arrays 25 | // Initial indexes of first and second subarrays 26 | int i = 0, j = 0; 27 | 28 | // Initial index of merged subarray array 29 | int k = l; 30 | while (i < n1 && j < n2) { 31 | if (L[i] <= R[j]) { 32 | arr[k] = L[i]; 33 | i++; 34 | } 35 | else { 36 | arr[k] = R[j]; 37 | j++; 38 | } 39 | k++; 40 | } 41 | 42 | // Copy remaining elements of L[] if any 43 | while (i < n1) { 44 | arr[k] = L[i]; 45 | i++; 46 | k++; 47 | } 48 | 49 | // Copy remaining elements of R[] if any 50 | while (j < n2) { 51 | arr[k] = R[j]; 52 | j++; 53 | k++; 54 | } 55 | } 56 | 57 | // Main function that sorts arr[l..r] using 58 | // merge() 59 | void sort(int arr[], int l, int r) 60 | { 61 | if (l < r) { 62 | // Find the middle point 63 | int m = (l + r) / 2; 64 | 65 | // Sort first and second halves 66 | sort(arr, l, m); 67 | sort(arr, m + 1, r); 68 | 69 | // Merge the sorted halves 70 | merge(arr, l, m, r); 71 | } 72 | } 73 | 74 | // A utility function to print array of size n 75 | static void printArray(int arr[]) 76 | { 77 | int n = arr.length; 78 | for (int i = 0; i < n; ++i) 79 | System.out.print(arr[i] + " "); 80 | System.out.println(); 81 | } 82 | 83 | // Driver method 84 | public static void main(String args[]) 85 | { 86 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 87 | 88 | System.out.println("Given Array"); 89 | printArray(arr); 90 | 91 | // Calling of Merge Sort 92 | MergeSort ob = new MergeSort(); 93 | ob.sort(arr, 0, arr.length - 1); 94 | 95 | System.out.println("\nSorted array"); 96 | printArray(arr); 97 | } 98 | } 99 | 100 | /* 101 | Given Array 102 | 12 11 13 5 6 7 103 | 104 | Sorted array 105 | 5 6 7 11 12 13 106 | 107 | Time Complexity: O(n logn) 108 | 109 | Auxiliary Space: O(n) 110 | */ 111 | -------------------------------------------------------------------------------- /Merge Sort Algorithm/JavaScript/MergeSort.js: -------------------------------------------------------------------------------- 1 | function merge(arr, beg, mid, end) { 2 | const l = mid - beg + 1; 3 | const r = end - mid; 4 | const LeftArray = new Array(l); 5 | const RightArray = new Array(r); 6 | 7 | for (let i = 0; i < l; ++i) 8 | LeftArray[i] = arr[beg + i]; 9 | for (let j = 0; j < r; ++j) 10 | RightArray[j] = arr[mid + 1 + j]; 11 | 12 | let i = 0, j = 0; 13 | let k = beg; 14 | 15 | while (i < l && j < r) { 16 | if (LeftArray[i] <= RightArray[j]) { 17 | arr[k] = LeftArray[i]; 18 | i++; 19 | } else { 20 | arr[k] = RightArray[j]; 21 | j++; 22 | } 23 | k++; 24 | } 25 | 26 | while (i < l) { 27 | arr[k] = LeftArray[i]; 28 | i++; 29 | k++; 30 | } 31 | 32 | while (j < r) { 33 | arr[k] = RightArray[j]; 34 | j++; 35 | k++; 36 | } 37 | } 38 | 39 | function mergeSort(arr, beg, end) { 40 | if (beg < end) { 41 | const mid = Math.floor((beg + end) / 2); 42 | mergeSort(arr, beg, mid); 43 | mergeSort(arr, mid + 1, end); 44 | merge(arr, beg, mid, end); 45 | } 46 | } 47 | 48 | function main() { 49 | const arr = [40, 51, 22, 45, 1, 4, 90, 23, 17, 55]; 50 | mergeSort(arr, 0, arr.length - 1); 51 | console.log("Sorted array:"); 52 | for (let i = 0; i < arr.length; i++) { 53 | console.log(arr[i] + ""); 54 | } 55 | } 56 | 57 | main(); -------------------------------------------------------------------------------- /Merge Sort Algorithm/Python/merge_sort.py: -------------------------------------------------------------------------------- 1 | def mergeSort(arr): 2 | 3 | if len(arr) > 1: 4 | a = len(arr)//2 5 | l = arr[:a] 6 | r = arr[a:] 7 | 8 | mergeSort(l) 9 | mergeSort(r) 10 | b = c = d = 0 11 | 12 | while b < len(l) and c < len(r): 13 | if l[b] < r[c]: 14 | arr[d] = l[b] 15 | b += 1 16 | 17 | else: 18 | arr[d] = r[c] 19 | c += 1 20 | d += 1 21 | 22 | while b < len(l): 23 | arr[d] = l[b] 24 | b += 1 25 | d += 1 26 | while c < len(r): 27 | arr[d] = r[c] 28 | c += 1 29 | d += 1 30 | 31 | 32 | def printList(arr): 33 | for i in range(len(arr)): 34 | print(arr[i], end=" ") 35 | print() 36 | 37 | if __name__ == '__main__': 38 | arr = [0,1,3,5,7,9,2,4,6,8] 39 | mergeSort(arr) 40 | print("Sorted array is: ") 41 | printList(arr) -------------------------------------------------------------------------------- /Merge Sort Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Merge Sort Algorithm 2 | 3 | Merge Sort is a divide-and-conquer sorting algorithm that works by recursively dividing the input array into two halves, sorting each half, and then merging the two sorted halves back together. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n _ log(n)) 8 | Average: O(n _ log(n)) 9 | Worst: O(n \* log(n)) 10 | 11 | ## Space Complexity 12 | 13 | O(n) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a large dataset when a stable sort is required, such as sorting a list of customers by last name and then by first name, or sorting a list of transactions by date and then by amount. 18 | -------------------------------------------------------------------------------- /Palindrome.java: -------------------------------------------------------------------------------- 1 | class example{ 2 | public static void main(String args[]){ 3 | int r,sum=0,temp; 4 | int n=100; 5 | temp=n; 6 | while(n>0){ 7 | r=n%10; 8 | sum=(sum*10)+r; 9 | n=n/10; 10 | } 11 | if(temp==sum) 12 | System.out.println("palindrome"); 13 | else 14 | System.out.println("not palindrome"); 15 | } 16 | } 17 | 18 | 19 | class Solution { 20 | public boolean isPalindrome(int x) { 21 | int temp=x; 22 | int rev=0; 23 | 24 | while(x>0) 25 | { 26 | int rem=x%10; 27 | rev=(rev*10)+rem; 28 | x=x/10; 29 | } 30 | if(rev==temp) 31 | return true; 32 | else 33 | return false; 34 | 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /PrimeNumberfinder.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() { 5 | 6 | int i, n; 7 | bool is_prime = true; 8 | 9 | cout << "Enter a positive integer: "; 10 | cin >> n; 11 | 12 | // 0 and 1 are not prime numbers 13 | if (n == 0 || n == 1) { 14 | is_prime = false; 15 | } 16 | 17 | // loop to check if n is prime 18 | for (i = 2; i <= n/2; ++i) { 19 | if (n % i == 0) { 20 | is_prime = false; 21 | break; 22 | } 23 | } 24 | 25 | if (is_prime) 26 | cout << n << " is a prime number"; 27 | else 28 | cout << n << " is not a prime number"; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Quickselect Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Quickselect Algorithm 2 | 3 | Quickselect is a selection algorithm that finds the k-th smallest element in an unsorted array. It is based on the partitioning step of the QuickSort algorithm and works by selecting a pivot and partitioning the array around the pivot. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n) 8 | Average: O(n) 9 | Worst: O(n^2) 10 | 11 | ## Space Complexity 12 | 13 | O(log(n)) 14 | 15 | ## Example Use Case 16 | 17 | Finding the k-th smallest element in an unsorted array, such as finding the median or any other order statistic in a dataset. 18 | -------------------------------------------------------------------------------- /Quicksort Algorithm/C++/Quick Sort Algorithm: -------------------------------------------------------------------------------- 1 | // C++ Implementation of the Quick Sort Algorithm. 2 | #include 3 | using namespace std; 4 | 5 | int partition(int arr[], int start, int end) 6 | { 7 | 8 | int pivot = arr[start]; 9 | 10 | int count = 0; 11 | for (int i = start + 1; i <= end; i++) { 12 | if (arr[i] <= pivot) 13 | count++; 14 | } 15 | 16 | // Giving pivot element its correct position 17 | int pivotIndex = start + count; 18 | swap(arr[pivotIndex], arr[start]); 19 | 20 | // Sorting left and right parts of the pivot element 21 | int i = start, j = end; 22 | 23 | while (i < pivotIndex && j > pivotIndex) { 24 | 25 | while (arr[i] <= pivot) { 26 | i++; 27 | } 28 | 29 | while (arr[j] > pivot) { 30 | j--; 31 | } 32 | 33 | if (i < pivotIndex && j > pivotIndex) { 34 | swap(arr[i++], arr[j--]); 35 | } 36 | } 37 | 38 | return pivotIndex; 39 | } 40 | 41 | void quickSort(int arr[], int start, int end) 42 | { 43 | 44 | // base case 45 | if (start >= end) 46 | return; 47 | 48 | // partitioning the array 49 | int p = partition(arr, start, end); 50 | 51 | // Sorting the left part 52 | quickSort(arr, start, p - 1); 53 | 54 | // Sorting the right part 55 | quickSort(arr, p + 1, end); 56 | } 57 | 58 | int main() 59 | { 60 | 61 | int arr[] = { 9, 3, 4, 2, 1, 8 }; 62 | int n = 6; 63 | 64 | quickSort(arr, 0, n - 1); 65 | 66 | for (int i = 0; i < n; i++) { 67 | cout << arr[i] << " "; 68 | } 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /Quicksort Algorithm/C/quick_sort.c: -------------------------------------------------------------------------------- 1 | // Quick sort in C 2 | 3 | #include 4 | 5 | // function to swap elements 6 | void swap(int *a, int *b) { 7 | int t = *a; 8 | *a = *b; 9 | *b = t; 10 | } 11 | 12 | // function to find the partition position 13 | int partition(int array[], int low, int high) { 14 | 15 | // select the rightmost element as pivot 16 | int pivot = array[high]; 17 | 18 | // pointer for greater element 19 | int i = (low - 1); 20 | 21 | // traverse each element of the array 22 | // compare them with the pivot 23 | for (int j = low; j < high; j++) { 24 | if (array[j] <= pivot) { 25 | 26 | // if element smaller than pivot is found 27 | // swap it with the greater element pointed by i 28 | i++; 29 | 30 | // swap element at i with element at j 31 | swap(&array[i], &array[j]); 32 | } 33 | } 34 | 35 | // swap the pivot element with the greater element at i 36 | swap(&array[i + 1], &array[high]); 37 | 38 | // return the partition point 39 | return (i + 1); 40 | } 41 | 42 | void quickSort(int array[], int low, int high) { 43 | if (low < high) { 44 | 45 | // find the pivot element such that 46 | // elements smaller than pivot are on left of pivot 47 | // elements greater than pivot are on right of pivot 48 | int pi = partition(array, low, high); 49 | 50 | // recursive call on the left of pivot 51 | quickSort(array, low, pi - 1); 52 | 53 | // recursive call on the right of pivot 54 | quickSort(array, pi + 1, high); 55 | } 56 | } 57 | 58 | // function to print array elements 59 | void printArray(int array[], int size) { 60 | for (int i = 0; i < size; ++i) { 61 | printf("%d ", array[i]); 62 | } 63 | printf("\n"); 64 | } 65 | 66 | // main function 67 | int main() { 68 | int data[] = {8, 7, 2, 1, 0, 9, 6}; 69 | 70 | int n = sizeof(data) / sizeof(data[0]); 71 | 72 | printf("Unsorted Array\n"); 73 | printArray(data, n); 74 | 75 | // perform quicksort on data 76 | quickSort(data, 0, n - 1); 77 | 78 | printf("Sorted array in ascending order: \n"); 79 | printArray(data, n); 80 | } -------------------------------------------------------------------------------- /Quicksort Algorithm/Go/quick_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | func main() { 10 | 11 | slice := generateSlice(20) 12 | fmt.Println("\n--- Unsorted --- \n\n", slice) 13 | quicksort(slice) 14 | fmt.Println("\n--- Sorted ---\n\n", slice, "\n") 15 | } 16 | 17 | // Generates a slice of size, size filled with random numbers 18 | func generateSlice(size int) []int { 19 | 20 | slice := make([]int, size, size) 21 | rand.Seed(time.Now().UnixNano()) 22 | for i := 0; i < size; i++ { 23 | slice[i] = rand.Intn(999) - rand.Intn(999) 24 | } 25 | return slice 26 | } 27 | 28 | func quicksort(a []int) []int { 29 | if len(a) < 2 { 30 | return a 31 | } 32 | 33 | left, right := 0, len(a)-1 34 | 35 | pivot := rand.Int() % len(a) 36 | 37 | a[pivot], a[right] = a[right], a[pivot] 38 | 39 | for i, _ := range a { 40 | if a[i] < a[right] { 41 | a[left], a[i] = a[i], a[left] 42 | left++ 43 | } 44 | } 45 | 46 | a[left], a[right] = a[right], a[left] 47 | 48 | quicksort(a[:left]) 49 | quicksort(a[left+1:]) 50 | 51 | return a 52 | } -------------------------------------------------------------------------------- /Quicksort Algorithm/Java/QuickSort.java: -------------------------------------------------------------------------------- 1 | package Java; 2 | class QuickSort { 3 | // Partition Method 4 | int partition(int arr[], int lowIndex, int highIndex) { 5 | int pivot = arr[highIndex]; 6 | int i = (lowIndex - 1); 7 | for (int j = lowIndex; j < highIndex; j++) { 8 | if (arr[j] <= pivot) { 9 | i++; 10 | int temp = arr[i]; 11 | arr[i] = arr[j]; 12 | arr[j] = temp; 13 | } 14 | } 15 | int temp = arr[i + 1]; 16 | arr[i + 1] = arr[highIndex]; 17 | arr[highIndex] = temp; 18 | return i + 1; 19 | } 20 | 21 | // Sorting Method 22 | void sort(int arr[], int lowIndex, int highIndex) { 23 | if (lowIndex < highIndex) { 24 | int pi = partition(arr, lowIndex, highIndex); 25 | sort(arr, lowIndex, pi - 1); 26 | sort(arr, pi + 1, highIndex); 27 | } 28 | } 29 | 30 | // Method to print array 31 | static void printArray(int arr[]) { 32 | int n = arr.length; 33 | for (int i = 0; i < n; ++i) 34 | System.out.print(arr[i] + " "); 35 | System.out.println(); 36 | } 37 | 38 | // Main Method 39 | public static void main(String args[]) { 40 | int arr[] = { 101, 37, 68, 29, 11, 5 }; 41 | int n = arr.length; 42 | QuickSort ob = new QuickSort(); 43 | ob.sort(arr, 0, n - 1); 44 | System.out.println("sorted array"); 45 | printArray(arr); 46 | } 47 | } -------------------------------------------------------------------------------- /Quicksort Algorithm/JavaScript/QuickSort.js: -------------------------------------------------------------------------------- 1 | function quickSort(arr, left = 0, right = arr.length - 1) { 2 | if (left < right) { 3 | const pivotIndex = partition(arr, left, right); 4 | quickSort(arr, left, pivotIndex - 1); 5 | quickSort(arr, pivotIndex + 1, right); 6 | } 7 | return arr; 8 | } 9 | 10 | function partition(arr, left, right) { 11 | const pivot = arr[right]; 12 | let i = left - 1; 13 | for (let j = left; j < right; j++) { 14 | if (arr[j] < pivot) { 15 | i++; 16 | swap(arr, i, j); 17 | } 18 | } 19 | swap(arr, i + 1, right); 20 | return i + 1; 21 | } 22 | 23 | function swap(arr, i, j) { 24 | const temp = arr[i]; 25 | arr[i] = arr[j]; 26 | arr[j] = temp; 27 | } 28 | 29 | // Example usage: 30 | const arr = [5, 2, 9, 1, 5, 6]; 31 | const sortedArr = quickSort(arr); 32 | console.log(sortedArr); // [1, 2, 5, 5, 6, 9] 33 | -------------------------------------------------------------------------------- /Quicksort Algorithm/Python/QuickSort.py: -------------------------------------------------------------------------------- 1 | def quick_sort(arr): 2 | if len(arr) <= 1: 3 | return arr 4 | 5 | pivot = arr[len(arr) // 2] # Choose the pivot as the middle element 6 | left = [x for x in arr if x < pivot] 7 | middle = [x for x in arr if x == pivot] 8 | right = [x for x in arr if x > pivot] 9 | 10 | return quick_sort(left) + middle + quick_sort(right) 11 | 12 | # Example usage: 13 | my_list = [3, 6, 8, 10, 1, 2, 1] 14 | sorted_list = quick_sort(my_list) 15 | print(sorted_list) 16 | -------------------------------------------------------------------------------- /Quicksort Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Quicksort Algorithm 2 | 3 | Quicksort is a divide-and-conquer sorting algorithm that works by selecting a pivot element from the array and partitioning the other elements into two groups: those less than the pivot and those greater than the pivot. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n _ log(n)) 8 | Average: O(n _ log(n)) 9 | Worst: O(n^2) 10 | 11 | ## Space Complexity 12 | 13 | O(log(n)) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a large dataset when the worst-case performance is unlikely to be encountered, such as when the input data is randomly ordered or the pivot selection strategy is optimized. 18 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms Collection 2 | This repository contains a collection of various algorithms implemented in C, C++, Go, Java, JavaScript, and Python. The goal of this repository is to help fellow programmers learn and understand algorithms more effectively by providing code examples and explanations in multiple programming languages. 3 | 4 | ## List of Algorithms 5 | - Bellman-Ford Algorithm 6 | - Binary Search Algorithm 7 | - Boyer-Moore Majority Vote Algorithm 8 | - Breadth-First Search (BFS) Algorithm 9 | - Counting Sort Algorithm 10 | - Depth-First Search (DFS) Algorithm 11 | - Dijkstra's Algorithm 12 | - Euclid's Algorithm 13 | - Flood Fill Algorithm 14 | - Floyd-Warshall Algorithm 15 | - Heap Sort Algorithm 16 | - Huffman Coding Compression Algorithm 17 | - Insertion Sort Algorithm 18 | - Kadane's Algorithm 19 | - KMP Algorithm 20 | - Kruskal's Algorithm 21 | - Lee Algorithm 22 | - Merge Sort Algorithm 23 | - Quickselect Algorithm 24 | - Quicksort Algorithm 25 | - Selection Sort Algorithm 26 | - TopologicalSortAlgorithm 27 | - Union Find Algorithm 28 | ## Contributing 29 | Please check the [CONTRIBUTING.md](https://github.com/abhaysinghr516/Algorithms/blob/main/CONTRIBUTING.md) file for guidelines on how to contribute to this repository. 30 | -------------------------------------------------------------------------------- /Selection Sort Algortihm/README.md: -------------------------------------------------------------------------------- 1 | # Selection Sort Algorithm 2 | 3 | Selection Sort is a simple, comparison-based sorting algorithm that works by repeatedly finding the minimum or maximum element from the unsorted part of the array and moving it to the beginning or end of the sorted part. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(n^2) 8 | Average: O(n^2) 9 | Worst: O(n^2) 10 | 11 | ## Space Complexity 12 | 13 | O(1) 14 | 15 | ## Example Use Case 16 | 17 | Sorting a small dataset when the available memory is limited, as Selection Sort is an in-place sorting algorithm with a low space complexity. 18 | -------------------------------------------------------------------------------- /Selection Sort Algortihm/SelectionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swap(int *xp, int *yp) 4 | { 5 | int temp = *xp; 6 | *xp = *yp; 7 | *yp = temp; 8 | } 9 | 10 | void selectionSort(int arr[], int n) 11 | { 12 | int i, j, min_idx; 13 | 14 | for (i = 0; i < n-1; i++) 15 | { 16 | min_idx = i; 17 | for (j = i+1; j < n; j++) 18 | if (arr[j] < arr[min_idx]) 19 | min_idx = j; 20 | 21 | if(min_idx != i) 22 | swap(&arr[min_idx], &arr[i]); 23 | } 24 | } 25 | 26 | void printArray(int arr[], int size) 27 | { 28 | int i; 29 | for (i=0; i < size; i++) 30 | printf("%d ", arr[i]); 31 | printf("\n"); 32 | } 33 | 34 | int main() 35 | { 36 | int arr[] = {64, 25, 12, 22, 11}; 37 | int n = sizeof(arr)/sizeof(arr[0]); 38 | selectionSort(arr, n); 39 | printf("Sorted array: \n"); 40 | printArray(arr, n); 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Selection Sort Algortihm/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | 2 | // C++ program for implementation of 3 | // selection sort 4 | #include 5 | using namespace std; 6 | 7 | // Function for Selection sort 8 | void selectionSort(int arr[], int n) 9 | { 10 | int i, j, min_idx; 11 | 12 | // One by one move boundary of 13 | // unsorted subarray 14 | for (i = 0; i < n - 1; i++) { 15 | 16 | // Find the minimum element in 17 | // unsorted array 18 | min_idx = i; 19 | for (j = i + 1; j < n; j++) { 20 | if (arr[j] < arr[min_idx]) 21 | min_idx = j; 22 | } 23 | 24 | // Swap the found minimum element 25 | // with the first element 26 | if (min_idx != i) 27 | swap(arr[min_idx], arr[i]); 28 | } 29 | } 30 | 31 | // Function to print an array 32 | void printArray(int arr[], int size) 33 | { 34 | int i; 35 | for (i = 0; i < size; i++) { 36 | cout << arr[i] << " "; 37 | cout << endl; 38 | } 39 | } 40 | 41 | // Driver program 42 | int main() 43 | { 44 | int arr[] = { 64, 25, 12, 22, 11 }; 45 | int n = sizeof(arr) / sizeof(arr[0]); 46 | 47 | // Function Call 48 | selectionSort(arr, n); 49 | cout << "Sorted array: \n"; 50 | printArray(arr, n); 51 | return 0; 52 | } -------------------------------------------------------------------------------- /Selection Sort Algortihm/SelectionSort.java: -------------------------------------------------------------------------------- 1 | class SelectionSort { 2 | // Selection Sort Method 3 | void sort(int array[]) { 4 | int n = array.length; 5 | for (int i = 0; i < n - 1; i++) { 6 | int min_element = i; 7 | for (int j = i + 1; j < n; j++) 8 | if (array[j] < array[min_element]) 9 | min_element = j; 10 | int temp = array[min_element]; 11 | array[min_element] = array[i]; 12 | array[i] = temp; 13 | } 14 | } 15 | 16 | // Method to print the elements of an array 17 | void printarrayay(int array[]) { 18 | int n = array.length; 19 | for (int i = 0; i < n; ++i) 20 | System.out.print(array[i] + " "); 21 | System.out.println(); 22 | } 23 | 24 | // Main Method 25 | public static void main(String args[]) { 26 | SelectionSort ob = new SelectionSort(); 27 | int array[] = { 15, 10, 99, 53, 36 }; 28 | ob.sort(array); 29 | System.out.println("Sorted arrayay"); 30 | ob.printarrayay(array); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /Selection Sort Algortihm/SelectionSort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr) { 2 | for (let i = 0; i < arr.length - 1; i++) { 3 | let minIndex = i; 4 | for (let j = i + 1; j < arr.length; j++) { 5 | if (arr[j] < arr[minIndex]) { 6 | minIndex = j; 7 | } 8 | } 9 | if (minIndex !== i) { 10 | [arr[i], arr[minIndex]] = [arr[minIndex], arr[i]]; 11 | } 12 | } 13 | return arr; 14 | } 15 | 16 | const arr = [64, 25, 12, 22, 11]; 17 | console.log(selectionSort(arr)); // [11, 12, 22, 25, 64] 18 | -------------------------------------------------------------------------------- /Selection Sort Algortihm/SelectionSort.py: -------------------------------------------------------------------------------- 1 | # Selection sort in Python 2 | 3 | 4 | def selectionSort(array, size): 5 | 6 | for step in range(size): 7 | min_idx = step 8 | 9 | for i in range(step + 1, size): 10 | 11 | # to sort in descending order, change > to < in this line 12 | # select the minimum element in each loop 13 | if array[i] < array[min_idx]: 14 | min_idx = i 15 | 16 | # put min at the correct position 17 | (array[step], array[min_idx]) = (array[min_idx], array[step]) 18 | 19 | 20 | data = [-2, 45, 0, 11, -9] 21 | size = len(data) 22 | selectionSort(data, size) 23 | print('Sorted Array in Ascending Order:') 24 | print(data) -------------------------------------------------------------------------------- /Selection Sort Algortihm/selection_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func selectionSort(arr []int) { 6 | n := len(arr) 7 | 8 | for i := 0; i < n-1; i++ { 9 | // Find the minimum element in the unsorted portion 10 | minIndex := i 11 | for j := i + 1; j < n; j++ { 12 | if arr[j] < arr[minIndex] { 13 | minIndex = j 14 | } 15 | } 16 | 17 | // Swap the found minimum element with the first element in the unsorted portion 18 | arr[i], arr[minIndex] = arr[minIndex], arr[i] 19 | } 20 | } 21 | 22 | func main() { 23 | // Example unsorted slice 24 | unsorted := []int{64, 34, 25, 12, 22, 11, 90} 25 | 26 | fmt.Println("Unsorted slice:", unsorted) 27 | 28 | // Apply Selection Sort 29 | selectionSort(unsorted) 30 | 31 | fmt.Println("Sorted slice:", unsorted) 32 | } -------------------------------------------------------------------------------- /SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int SelectionSort(int arr[], int n) 6 | { 7 | int s=0; 8 | int e=n; 9 | while(s>n; 36 | 37 | int arr[n]; 38 | cout<<"\nEnter "<>arr[i]; 43 | } 44 | 45 | cout<<"\nBefore Sorting:"<> adjacencyList; 8 | 9 | public DirectedGraph(int vertices) { 10 | numberOfVertices = vertices; 11 | adjacencyList = new ArrayList<>(numberOfVertices); 12 | for (int i = 0; i < numberOfVertices; i++) { 13 | adjacencyList.add(new ArrayList<>()); 14 | } 15 | } 16 | 17 | public void addEdge(int source, int destination) { 18 | adjacencyList.get(source).add(destination); 19 | } 20 | 21 | private void performTopologicalSortUtil(int vertex, boolean[] visited, Stack stack) { 22 | visited[vertex] = true; 23 | for (Integer neighbor : adjacencyList.get(vertex)) { 24 | if (!visited[neighbor]) { 25 | performTopologicalSortUtil(neighbor, visited, stack); 26 | } 27 | } 28 | stack.push(vertex); 29 | } 30 | 31 | public void performTopologicalSort() { 32 | Stack topologicalOrderStack = new Stack<>(); 33 | boolean[] visited = new boolean[numberOfVertices]; 34 | 35 | Arrays.fill(visited, false); 36 | 37 | for (int vertex = 0; vertex < numberOfVertices; vertex++) { 38 | if (!visited[vertex]) { 39 | performTopologicalSortUtil(vertex, visited, topologicalOrderStack); 40 | } 41 | } 42 | 43 | // Print the topological order 44 | System.out.println("Topological Sort Order:"); 45 | while (!topologicalOrderStack.isEmpty()) { 46 | System.out.print(topologicalOrderStack.pop() + " "); 47 | } 48 | } 49 | 50 | public static void main(String[] args) { 51 | DirectedGraph graph = new DirectedGraph(6); 52 | graph.addEdge(5, 2); 53 | graph.addEdge(5, 0); 54 | graph.addEdge(4, 0); 55 | graph.addEdge(4, 1); 56 | graph.addEdge(2, 3); 57 | graph.addEdge(3, 1); 58 | 59 | System.out.println("Performing Topological Sort:"); 60 | graph.performTopologicalSort(); 61 | } 62 | } -------------------------------------------------------------------------------- /TopologicalSortAlgorithm/README.md: -------------------------------------------------------------------------------- 1 | # TopologicalSortAlgorithm 2 | 3 | Topological Sort is a linear ordering of the vertices of a directed acyclic graph (DAG) such that for every directed edge uv from vertex u to vertex v, u comes before v in the ordering. It is commonly used in scheduling tasks with dependencies or resolving the order of compilation for a set of files with dependencies. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(V + E) 8 | Average: O(V + E) 9 | Worst: O(V + E) 10 | 11 | ## Space Complexity 12 | 13 | O(V) 14 | 15 | ## Example Use Case 16 | 17 | Finding a valid sequence for a set of tasks with dependencies, such as determining the order in which courses should be taken in a curriculum, or scheduling tasks in a project with precedence constraints. 18 | -------------------------------------------------------------------------------- /TopologicalSortAlgorithm/Topo_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | void topologicalSortUtil(int v, vector &visited, stack &Stack, const vector> &adj) { 8 | visited[v] = true; 9 | 10 | for (int i : adj[v]) { 11 | if (!visited[i]) { 12 | topologicalSortUtil(i, visited, Stack, adj); 13 | } 14 | } 15 | 16 | Stack.push(v); 17 | } 18 | 19 | void topologicalSort(int V, const vector> &adj) { 20 | stack Stack; 21 | vector visited(V, false); 22 | 23 | for (int i = 0; i < V; i++) { 24 | if (!visited[i]) { 25 | topologicalSortUtil(i, visited, Stack, adj); 26 | } 27 | } 28 | 29 | while (!Stack.empty()) { 30 | cout << Stack.top() << " "; 31 | Stack.pop(); 32 | } 33 | } 34 | 35 | int main() { 36 | int V = 6; 37 | vector> adj(V); 38 | 39 | adj[5].push_back(2); 40 | adj[5].push_back(0); 41 | adj[4].push_back(0); 42 | adj[4].push_back(1); 43 | adj[2].push_back(3); 44 | adj[3].push_back(1); 45 | 46 | cout << "Topological Sort of the given graph: "; 47 | topologicalSort(V, adj); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /TopologicalSortAlgorithm/Topo_Sort.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | 3 | class Graph: 4 | def __init__(self, vertices): 5 | self.graph = defaultdict(list) 6 | self.V = vertices 7 | 8 | def add_edge(self, u, v): 9 | self.graph[u].append(v) 10 | 11 | def topological_sort_util(self, v, visited, stack): 12 | visited[v] = True 13 | 14 | for i in self.graph[v]: 15 | if not visited[i]: 16 | self.topological_sort_util(i, visited, stack) 17 | 18 | stack.insert(0, v) 19 | 20 | def topological_sort(self): 21 | visited = [False] * self.V 22 | stack = [] 23 | 24 | for i in range(self.V): 25 | if not visited[i]: 26 | self.topological_sort_util(i, visited, stack) 27 | 28 | print(stack) 29 | 30 | if __name__ == "__main__": 31 | g = Graph(6) 32 | g.add_edge(5, 2) 33 | g.add_edge(5, 0) 34 | g.add_edge(4, 0) 35 | g.add_edge(4, 1) 36 | g.add_edge(2, 3) 37 | g.add_edge(3, 1) 38 | 39 | print("Topological Sort of the given graph:") 40 | g.topological_sort() 41 | -------------------------------------------------------------------------------- /Tree Traversal/PostOrder_Traversal.java: -------------------------------------------------------------------------------- 1 | // Description 2 | 3 | // Postorder traversal is a way to visit and process the nodes in a tree data structure. 4 | // In postorder traversal, you start at the root node, recursively traverse the left subtree, 5 | // then recursively traverse the right subtree, and finally, visit the current node. 6 | // Here's a Java implementation of postorder traversal for a binary tree: 7 | 8 | 9 | // implementation 10 | 11 | class TreeNode { 12 | int data; 13 | TreeNode left; 14 | TreeNode right; 15 | 16 | public TreeNode(int data) { 17 | this.data = data; 18 | this.left = null; 19 | this.right = null; 20 | } 21 | } 22 | 23 | public class PostorderTraversal { 24 | public static void postorderTraversal(TreeNode node) { 25 | if (node != null) { 26 | // Recursively traverse the left subtree 27 | postorderTraversal(node.left); 28 | 29 | // Recursively traverse the right subtree 30 | postorderTraversal(node.right); 31 | 32 | // Visit the current node 33 | System.out.print(node.data + " "); 34 | } 35 | } 36 | 37 | public static void main(String[] args) { 38 | // Create a simple binary tree 39 | TreeNode root = new TreeNode(1); 40 | root.left = new TreeNode(2); 41 | root.right = new TreeNode(3); 42 | root.left.left = new TreeNode(4); 43 | root.left.right = new TreeNode(5); 44 | 45 | System.out.print("Postorder traversal: "); 46 | postorderTraversal(root); 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /Tree Traversal/PreOrder_Traversal.java: -------------------------------------------------------------------------------- 1 | // Description 2 | 3 | // Preorder traversal is a way to visit and process the nodes in a tree data structure. 4 | // In preorder traversal, you start at the root node, visit the current node, 5 | // then recursively traverse the left subtree, and finally, recursively traverse the right subtree. 6 | // Here's a Java implementation of preorder traversal for a binary tree: 7 | 8 | // implementation 9 | 10 | class TreeNode { 11 | int data; 12 | TreeNode left; 13 | TreeNode right; 14 | 15 | public TreeNode(int data) { 16 | this.data = data; 17 | this.left = null; 18 | this.right = null; 19 | } 20 | } 21 | 22 | public class PreorderTraversal { 23 | public static void preorderTraversal(TreeNode node) { 24 | if (node != null) { 25 | // Visit the current node 26 | System.out.print(node.data + " "); 27 | 28 | // Recursively traverse the left subtree 29 | preorderTraversal(node.left); 30 | 31 | // Recursively traverse the right subtree 32 | preorderTraversal(node.right); 33 | } 34 | } 35 | 36 | public static void main(String[] args) { 37 | // Create a simple binary tree 38 | TreeNode root = new TreeNode(1); 39 | root.left = new TreeNode(2); 40 | root.right = new TreeNode(3); 41 | root.left.left = new TreeNode(4); 42 | root.left.right = new TreeNode(5); 43 | 44 | System.out.print("Preorder traversal: "); 45 | preorderTraversal(root); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Union Find Algorithm/README.md: -------------------------------------------------------------------------------- 1 | # Union Find Algorithm 2 | 3 | Union Find, also known as Disjoint Set, is a data structure and algorithm that keeps track of a set of elements partitioned into disjoint, non-overlapping subsets. It supports two primary operations: Union, which merges two subsets into a single subset, and Find, which determines the representative element of a subset. 4 | 5 | ## Time Complexity 6 | 7 | Best: O(α(n)) for Union and Find operations with path compression and union by rank 8 | Average: O(α(n)) for Union and Find operations with path compression and union by rank 9 | Worst: O(α(n)) for Union and Find operations with path compression and union by rank 10 | 11 | ## Space Complexity 12 | 13 | O(n) 14 | 15 | ## Example Use Case 16 | 17 | Managing connected components in a graph, such as implementing Kruskal's algorithm for finding the minimum spanning tree or detecting cycles in an undirected graph. 18 | 19 | ![image](https://github.com/OsauravO/Algorithms/assets/123803605/28479e35-5224-463d-b2f5-636939c14a50) 20 | -------------------------------------------------------------------------------- /Union Find Algorithm/UnionFindAlgoC++.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of disjoint set 2 | #include 3 | using namespace std; 4 | class DisjointSet { 5 | int *rank, *parent, n; 6 | 7 | public: 8 | // Constructor to create and 9 | // initialize sets of n items 10 | DisjointSet(int n) 11 | { 12 | rank = new int[n]; 13 | parent = new int[n]; 14 | this->n = n; 15 | make_set(); 16 | } 17 | 18 | // Creates n single item sets 19 | void make_set() 20 | { 21 | for (int i = 0; i < n; i++) { 22 | parent[i] = i; 23 | } 24 | } 25 | 26 | // Finds set of given item x 27 | int find_set(int x) 28 | { 29 | // Finds the representative of the set 30 | // that x is an element of 31 | if (parent[x] != x) { 32 | 33 | // if x is not the parent of itself 34 | // Then x is not the representative of 35 | // his set, 36 | parent[x] = find_set(parent[x]); 37 | 38 | // so we recursively call Find on its parent 39 | // and move i's node directly under the 40 | // representative of this set 41 | } 42 | 43 | return parent[x]; 44 | } 45 | 46 | // Do union of two sets represented 47 | // by x and y. 48 | void Union(int x, int y) 49 | { 50 | // Find current sets of x and y 51 | int xset = find_set(x); 52 | int yset = find_set(y); 53 | 54 | // If they are already in same set 55 | if (xset == yset) 56 | return; 57 | 58 | // Put smaller ranked item under 59 | // bigger ranked item if ranks are 60 | // different 61 | if (rank[xset] < rank[yset]) { 62 | parent[xset] = yset; 63 | } 64 | else if (rank[xset] > rank[yset]) { 65 | parent[yset] = xset; 66 | } 67 | 68 | // If ranks are same, then increment 69 | // rank. 70 | else { 71 | parent[yset] = xset; 72 | rank[xset] = rank[xset] + 1; 73 | } 74 | } 75 | }; 76 | 77 | int main() 78 | { 79 | DisjointSet obj(5); 80 | obj.Union(0, 2); 81 | obj.Union(4, 2); 82 | obj.Union(3, 1); 83 | if (obj.find_set(4) == obj.find_set(0)) 84 | cout << "Yes\n"; 85 | else 86 | cout << "No\n"; 87 | if (obj.find_set(1) == obj.find_set(0)) 88 | cout << "Yes\n"; 89 | else 90 | cout << "No\n"; 91 | 92 | return 0; 93 | } -------------------------------------------------------------------------------- /Union Find Algorithm/union_find.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // Structure to represent a subset 5 | struct Subset { 6 | int parent; 7 | int rank; 8 | }; 9 | 10 | // Function to initialize subsets 11 | void makeSet(struct Subset subsets[], int n) { 12 | for (int i = 0; i < n; i++) { 13 | subsets[i].parent = i; 14 | subsets[i].rank = 0; 15 | } 16 | } 17 | 18 | // Find the root of a given element 'x' 19 | int find(struct Subset subsets[], int x) { 20 | if (subsets[x].parent != x) 21 | subsets[x].parent = find(subsets, subsets[x].parent); // Path compression 22 | return subsets[x].parent; 23 | } 24 | 25 | // Union two subsets based on rank 26 | void unionSets(struct Subset subsets[], int x, int y) { 27 | int rootX = find(subsets, x); 28 | int rootY = find(subsets, y); 29 | 30 | if (rootX != rootY) { 31 | if (subsets[rootX].rank < subsets[rootY].rank) 32 | subsets[rootX].parent = rootY; 33 | else if (subsets[rootX].rank > subsets[rootY].rank) 34 | subsets[rootY].parent = rootX; 35 | else { 36 | subsets[rootY].parent = rootX; 37 | subsets[rootX].rank++; 38 | } 39 | } 40 | } 41 | 42 | int main() { 43 | int n = 6; // Number of elements 44 | 45 | struct Subset subsets[n]; 46 | makeSet(subsets, n); 47 | 48 | // Perform some union operations 49 | unionSets(subsets, 0, 1); 50 | unionSets(subsets, 1, 2); 51 | unionSets(subsets, 3, 4); 52 | 53 | // Check if elements are in the same subset 54 | printf("Are 0 and 2 in the same subset? %s\n", (find(subsets, 0) == find(subsets, 2)) ? "Yes" : "No"); 55 | printf("Are 0 and 4 in the same subset? %s\n", (find(subsets, 0) == find(subsets, 4)) ? "Yes" : "No"); 56 | 57 | return 0; 58 | } -------------------------------------------------------------------------------- /Union Find Algorithm/union_find.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type UnionFind struct { 6 | parent []int 7 | rank []int 8 | } 9 | 10 | func NewUnionFind(n int) *UnionFind { 11 | parent := make([]int, n) 12 | rank := make([]int, n) 13 | for i := 0; i < n; i++ { 14 | parent[i] = i 15 | rank[i] = 0 16 | } 17 | return &UnionFind{parent, rank} 18 | } 19 | 20 | func (uf *UnionFind) Find(x int) int { 21 | if uf.parent[x] != x { 22 | uf.parent[x] = uf.Find(uf.parent[x]) // Path compression 23 | } 24 | return uf.parent[x] 25 | } 26 | 27 | func (uf *UnionFind) Union(x, y int) { 28 | rootX := uf.Find(x) 29 | rootY := uf.Find(y) 30 | 31 | if rootX == rootY { 32 | return 33 | } 34 | 35 | if uf.rank[rootX] < uf.rank[rootY] { 36 | uf.parent[rootX] = rootY 37 | } else if uf.rank[rootX] > uf.rank[rootY] { 38 | uf.parent[rootY] = rootX 39 | } else { 40 | uf.parent[rootY] = rootX 41 | uf.rank[rootX]++ 42 | } 43 | } 44 | 45 | func main() { 46 | n := 6 // Number of elements 47 | 48 | uf := NewUnionFind(n) 49 | 50 | // Perform some union operations 51 | uf.Union(0, 1) 52 | uf.Union(1, 2) 53 | uf.Union(3, 4) 54 | uf.Union(4, 5) 55 | 56 | // Check if elements are in the same set 57 | fmt.Println("Are 0 and 2 in the same set?", uf.Find(0) == uf.Find(2)) // Should print true 58 | fmt.Println("Are 1 and 3 in the same set?", uf.Find(1) == uf.Find(3)) // Should print false 59 | } -------------------------------------------------------------------------------- /Union Find Algorithm/union_find.java: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | private int[] parent; 3 | private int[] rank; 4 | 5 | public UnionFind(int n) { 6 | parent = new int[n]; 7 | rank = new int[n]; 8 | 9 | for (int i = 0; i < n; i++) { 10 | parent[i] = i; 11 | rank[i] = 0; 12 | } 13 | } 14 | 15 | public int find(int x) { 16 | if (parent[x] != x) { 17 | parent[x] = find(parent[x]); 18 | } 19 | return parent[x]; 20 | } 21 | 22 | public void union(int x, int y) { 23 | int rootX = find(x); 24 | int rootY = find(y); 25 | 26 | if (rootX == rootY) { 27 | return; 28 | } 29 | 30 | if (rank[rootX] < rank[rootY]) { 31 | parent[rootX] = rootY; 32 | } else if (rank[rootX] > rank[rootY]) { 33 | parent[rootY] = rootX; 34 | } else { 35 | parent[rootY] = rootX; 36 | rank[rootX]++; 37 | } 38 | } 39 | } 40 | 41 | public class Main { 42 | public static void main(String[] args) { 43 | int n = 6; 44 | UnionFind uf = new UnionFind(n); 45 | 46 | uf.union(0, 1); 47 | uf.union(1, 2); 48 | uf.union(3, 4); 49 | uf.union(4, 5); 50 | 51 | System.out.println("Are 0 and 2 in the same set? " + (uf.find(0) == uf.find(2))); // Should be true 52 | System.out.println("Are 1 and 5 in the same set? " + (uf.find(1) == uf.find(5))); // Should be false 53 | } 54 | } -------------------------------------------------------------------------------- /Union Find Algorithm/union_find.js: -------------------------------------------------------------------------------- 1 | class UnionFind { 2 | constructor(size) { 3 | this.parent = new Array(size); 4 | this.rank = new Array(size).fill(0); 5 | 6 | for (let i = 0; i < size; i++) { 7 | this.parent[i] = i; 8 | } 9 | } 10 | 11 | find(x) { 12 | if (this.parent[x] !== x) { 13 | this.parent[x] = this.find(this.parent[x]); // Path compression 14 | } 15 | return this.parent[x]; 16 | } 17 | 18 | union(x, y) { 19 | const rootX = this.find(x); 20 | const rootY = this.find(y); 21 | 22 | if (rootX !== rootY) { 23 | if (this.rank[rootX] > this.rank[rootY]) { 24 | this.parent[rootY] = rootX; 25 | } else if (this.rank[rootX] < this.rank[rootY]) { 26 | this.parent[rootX] = rootY; 27 | } else { 28 | this.parent[rootY] = rootX; 29 | this.rank[rootX]++; 30 | } 31 | } 32 | } 33 | } 34 | 35 | const size = 6; 36 | const uf = new UnionFind(size); 37 | 38 | uf.union(0, 1); 39 | uf.union(1, 2); 40 | uf.union(3, 4); 41 | uf.union(4, 5); 42 | 43 | console.log(uf.find(2) === uf.find(0)); 44 | console.log(uf.find(3) === uf.find(5)); 45 | -------------------------------------------------------------------------------- /Union Find Algorithm/union_find.py: -------------------------------------------------------------------------------- 1 | class UnionFind: 2 | def __init__(self, size): 3 | self.parent = list(range(size)) 4 | self.rank = [1] * size 5 | 6 | def find(self, p): 7 | if self.parent[p] != p: 8 | self.parent[p] = self.find(self.parent[p]) # Path compression 9 | return self.parent[p] 10 | 11 | def union(self, p, q): 12 | rootP = self.find(p) 13 | rootQ = self.find(q) 14 | if rootP != rootQ: 15 | if self.rank[rootP] > self.rank[rootQ]: 16 | self.parent[rootQ] = rootP 17 | elif self.rank[rootP] < self.rank[rootQ]: 18 | self.parent[rootP] = rootQ 19 | else: 20 | self.parent[rootQ] = rootP 21 | self.rank[rootP] += 1 22 | 23 | # Example usage 24 | uf = UnionFind(10) 25 | uf.union(1, 2) 26 | uf.union(3, 4) 27 | print(uf.find(1)) # Output: 1 28 | print(uf.find(2)) # Output: 1 29 | print(uf.find(3)) # Output: 3 30 | print(uf.find(4)) # Output: 3 31 | -------------------------------------------------------------------------------- /bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | 9 | int arr[n]; 10 | for(int i=0;i>arr[i]; 12 | } 13 | 14 | int counter = 1; 15 | while (counterarr[i+1]){ 18 | int temp = arr[i]; 19 | arr[i] = arr[i+1]; 20 | arr[i+1] = temp; 21 | } 22 | } 23 | counter++; 24 | } 25 | for (int i = 0; i < n; i++) 26 | { 27 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n; 7 | cin>>n; 8 | 9 | int arr[n]; 10 | for(int i =0;i>arr[i]; 12 | } 13 | 14 | for(int i=1;icurrent && j>=0){ 18 | arr[j+1] = arr[j]; 19 | j--; 20 | } 21 | arr[j+1]=current; 22 | } 23 | 24 | for(int i=0;i 3 | using namespace std; 4 | 5 | int maxSubarraySum(int arr[], int n) { 6 | int maxi = INT_MIN; // maximum sum 7 | 8 | for (int i = 0; i < n; i++) { 9 | int sum = 0; 10 | for (int j = i; j < n; j++) { 11 | // current subarray = arr[i.....j] 12 | 13 | //add the current element arr[j] 14 | // to the sum i.e. sum of arr[i...j-1] 15 | sum += arr[j]; 16 | 17 | maxi = max(maxi, sum); // getting the maximum 18 | } 19 | } 20 | 21 | return maxi; 22 | } 23 | 24 | int main() 25 | { 26 | int arr[] = { -2, 1, -3, 4, -1, 2, 1, -5, 4}; 27 | int n = sizeof(arr) / sizeof(arr[0]); 28 | int maxSum = maxSubarraySum(arr, n); 29 | cout << "The maximum subarray sum is: " << maxSum << endl; 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /palindromeNumber.cpp: -------------------------------------------------------------------------------- 1 | /*Given an integer x, return true if x is a palindrome, and false otherwise. 2 | 3 | Example 1: 4 | 5 | Input: x = 121 6 | Output: true 7 | Explanation: 121 reads as 121 from left to right and from right to left. 8 | 9 | 10 | Example 2: 11 | 12 | Input: x = -121 13 | Output: false 14 | Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome. 15 | 16 | 17 | Example 3: 18 | 19 | Input: x = 10 20 | Output: false 21 | Explanation: Reads 01 from right to left. Therefore it is not a palindrome. 22 | */ 23 | #include 24 | using namespace std; 25 | bool isPalindrome(long long int x) { 26 | if(x<0) 27 | return false; 28 | long long int x1=x; 29 | long long int rev=0; 30 | while(x1>0) 31 | { 32 | int dig=x1%10; 33 | rev=rev*10+dig; 34 | x1=x1/10; 35 | 36 | } 37 | 38 | if(rev==x) 39 | return true; 40 | return false; 41 | } 42 | -------------------------------------------------------------------------------- /quickSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class quickSort{ 4 | 5 | public static void main(String[] args) { 6 | 7 | int[] arr = {3,4,2,1}; 8 | quick(arr, 0, arr.length-1); 9 | System.out.println(Arrays.toString(arr)); 10 | } 11 | 12 | static void quick(int[] arr, int low, int high){ 13 | if(low >= high){ 14 | return; 15 | } 16 | int start = low; 17 | int end = high; 18 | int mid = low + (high - low) / 2; 19 | int pivot = arr[mid]; 20 | 21 | while(start <= end){ 22 | while(arr[start] < pivot){ 23 | start++; 24 | } 25 | while(arr[end] > pivot){ 26 | end--; 27 | } 28 | if(start <= end){ 29 | int tmp = arr[start]; 30 | arr[start] = arr[end]; 31 | arr[end] = tmp; 32 | start++; 33 | end--; 34 | } 35 | } 36 | 37 | quick(arr,low,end); 38 | quick(arr,start,high); 39 | } 40 | } 41 | --------------------------------------------------------------------------------