From 40df3b9ae570badebeee553acbed445cbcef7ed8 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sat, 8 Oct 2022 23:31:05 +0530 Subject: [PATCH 1/9] Create Dijsktras Algorithm Usage --- Dijsktras Algorithm Usage | 107 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 Dijsktras Algorithm Usage diff --git a/Dijsktras Algorithm Usage b/Dijsktras Algorithm Usage new file mode 100644 index 0000000..611e8bd --- /dev/null +++ b/Dijsktras Algorithm Usage @@ -0,0 +1,107 @@ +// C++ program for Dijkstra's single source shortest path +// algorithm. The program is for adjacency matrix +// representation of the graph +#include +using namespace std; +#include + +// Number of vertices in the graph +#define V 9 + +// A utility function to find the vertex with minimum +// distance value, from the set of vertices not yet included +// in shortest path tree +int minDistance(int dist[], bool sptSet[]) +{ + + // Initialize min value + int min = INT_MAX, min_index; + + for (int v = 0; v < V; v++) + if (sptSet[v] == false && dist[v] <= min) + min = dist[v], min_index = v; + + return min_index; +} + +// A utility function to print the constructed distance +// array +void printSolution(int dist[]) +{ + cout << "Vertex \t Distance from Source" << endl; + for (int i = 0; i < V; i++) + cout << i << " \t\t\t\t" << dist[i] << endl; +} + +// Function that implements Dijkstra's single source +// shortest path algorithm for a graph represented using +// adjacency matrix representation +void dijkstra(int graph[V][V], int src) +{ + int dist[V]; // The output array. dist[i] will hold the + // shortest + // distance from src to i + + bool sptSet[V]; // sptSet[i] will be true if vertex i is + // included in shortest + // path tree or shortest distance from src to i is + // finalized + + // Initialize all distances as INFINITE and stpSet[] as + // false + for (int i = 0; i < V; i++) + dist[i] = INT_MAX, sptSet[i] = false; + + // Distance of source vertex from itself is always 0 + dist[src] = 0; + + // Find shortest path for all vertices + for (int count = 0; count < V - 1; count++) { + // Pick the minimum distance vertex from the set of + // vertices not yet processed. u is always equal to + // src in the first iteration. + int u = minDistance(dist, sptSet); + + // Mark the picked vertex as processed + sptSet[u] = true; + + // Update dist value of the adjacent vertices of the + // picked vertex. + for (int v = 0; v < V; v++) + + // Update dist[v] only if is not in sptSet, + // there is an edge from u to v, and total + // weight of path from src to v through u is + // smaller than current value of dist[v] + if (!sptSet[v] && graph[u][v] + && dist[u] != INT_MAX + && dist[u] + graph[u][v] < dist[v]) + dist[v] = dist[u] + graph[u][v]; + } + + // print the constructed distance array + printSolution(dist); +} + +// driver's code +int main() +{ + + /* Let us create the example graph discussed above */ + int graph[V][V] = { { 0, 4, 0, 0, 0, 0, 0, 8, 0 }, + { 4, 0, 8, 0, 0, 0, 0, 11, 0 }, + { 0, 8, 0, 7, 0, 4, 0, 0, 2 }, + { 0, 0, 7, 0, 9, 14, 0, 0, 0 }, + { 0, 0, 0, 9, 0, 10, 0, 0, 0 }, + { 0, 0, 4, 14, 10, 0, 2, 0, 0 }, + { 0, 0, 0, 0, 0, 2, 0, 1, 6 }, + { 8, 11, 0, 0, 0, 0, 1, 0, 7 }, + { 0, 0, 2, 0, 0, 0, 6, 7, 0 } }; + + // Function call + dijkstra(graph, 0); + + return 0; +} + +// This code is contributed by shivanisinghss2110 From dd4264d9a92108af7b23b07b47670ef5eec72432 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sat, 8 Oct 2022 23:37:32 +0530 Subject: [PATCH 2/9] Create heap implementation --- heap implementation | 159 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 159 insertions(+) create mode 100644 heap implementation diff --git a/heap implementation b/heap implementation new file mode 100644 index 0000000..9112c19 --- /dev/null +++ b/heap implementation @@ -0,0 +1,159 @@ +// A C++ program to demonstrate common Binary Heap Operations +#include +#include +using namespace std; + +// Prototype of a utility function to swap two integers +void swap(int *x, int *y); + +// A class for Min Heap +class MinHeap +{ + int *harr; // pointer to array of elements in heap + int capacity; // maximum possible size of min heap + int heap_size; // Current number of elements in min heap +public: + // Constructor + MinHeap(int capacity); + + // to heapify a subtree with the root at given index + void MinHeapify(int ); + + int parent(int i) { return (i-1)/2; } + + // to get index of left child of node at index i + int left(int i) { return (2*i + 1); } + + // to get index of right child of node at index i + int right(int i) { return (2*i + 2); } + + // to extract the root which is the minimum element + int extractMin(); + + // Decreases key value of key at index i to new_val + void decreaseKey(int i, int new_val); + + // Returns the minimum key (key at root) from min heap + int getMin() { return harr[0]; } + + // Deletes a key stored at index i + void deleteKey(int i); + + // Inserts a new key 'k' + void insertKey(int k); +}; + +// Constructor: Builds a heap from a given array a[] of given size +MinHeap::MinHeap(int cap) +{ + heap_size = 0; + capacity = cap; + harr = new int[cap]; +} + +// Inserts a new key 'k' +void MinHeap::insertKey(int k) +{ + if (heap_size == capacity) + { + cout << "\nOverflow: Could not insertKey\n"; + return; + } + + // First insert the new key at the end + heap_size++; + int i = heap_size - 1; + harr[i] = k; + + // Fix the min heap property if it is violated + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Decreases value of key at index 'i' to new_val. It is assumed that +// new_val is smaller than harr[i]. +void MinHeap::decreaseKey(int i, int new_val) +{ + harr[i] = new_val; + while (i != 0 && harr[parent(i)] > harr[i]) + { + swap(&harr[i], &harr[parent(i)]); + i = parent(i); + } +} + +// Method to remove minimum element (or root) from min heap +int MinHeap::extractMin() +{ + if (heap_size <= 0) + return INT_MAX; + if (heap_size == 1) + { + heap_size--; + return harr[0]; + } + + // Store the minimum value, and remove it from heap + int root = harr[0]; + harr[0] = harr[heap_size-1]; + heap_size--; + MinHeapify(0); + + return root; +} + + +// This function deletes key at index i. It first reduced value to minus +// infinite, then calls extractMin() +void MinHeap::deleteKey(int i) +{ + decreaseKey(i, INT_MIN); + extractMin(); +} + +// A recursive method to heapify a subtree with the root at given index +// This method assumes that the subtrees are already heapified +void MinHeap::MinHeapify(int i) +{ + int l = left(i); + int r = right(i); + int smallest = i; + if (l < heap_size && harr[l] < harr[i]) + smallest = l; + if (r < heap_size && harr[r] < harr[smallest]) + smallest = r; + if (smallest != i) + { + swap(&harr[i], &harr[smallest]); + MinHeapify(smallest); + } +} + +// A utility function to swap two elements +void swap(int *x, int *y) +{ + int temp = *x; + *x = *y; + *y = temp; +} + +// Driver program to test above functions +int main() +{ + MinHeap h(11); + h.insertKey(3); + h.insertKey(2); + h.deleteKey(1); + h.insertKey(15); + h.insertKey(5); + h.insertKey(4); + h.insertKey(45); + cout << h.extractMin() << " "; + cout << h.getMin() << " "; + h.decreaseKey(2, 1); + cout << h.getMin(); + return 0; +} From a949184a0383ca21e5452f34e06d5dcd7ebe6c7d Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sat, 8 Oct 2022 23:38:55 +0530 Subject: [PATCH 3/9] Create implement dynamic queue --- implement dynamic queue | 293 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 293 insertions(+) create mode 100644 implement dynamic queue diff --git a/implement dynamic queue b/implement dynamic queue new file mode 100644 index 0000000..4a5ac10 --- /dev/null +++ b/implement dynamic queue @@ -0,0 +1,293 @@ +// C++ program for the above approach +#include +using namespace std; + +// Class definition for queue +template +class Queue { + +private: + // Stores the frontIndex + int frontIndex; + + // Stores the back Index + int backIndex; + + // Stores the array + X* arr; + + // Stores the sizeof queue + int sizeVar; + + // Stores the size of array + int capacityVar = 4; + +public: + // Queue class constructor + Queue() + { + arr = new X[capacityVar]; + frontIndex = backIndex = -1; + sizeVar = 0; + } + + // Function Methods + bool empty(); + bool full(); + void push(X x); + void pop(); + X front(); + X back(); + int capacity(); + int size(); +}; + +// Find the capacity of queue +template +int Queue::capacity() +{ + return capacityVar; +} + +// Find the number of elements +// present in Queue +template +int Queue::size() +{ + return sizeVar; +} + +// Function to check if +// Queue is empty or not +template +bool Queue::empty() +{ + if (frontIndex == -1 + && backIndex == -1) + return true; + else + return false; +} + +// Function to check if the queue +// is full or not +template +bool Queue::full() +{ + if (sizeVar == capacityVar) + return true; + else + return false; +} + +// Function to find the front element +// of the queue +template +X Queue::front() +{ + // If queue is empty + if (empty()) { + cout << "Queue underflow" + << endl; + abort(); + } + + return arr[frontIndex]; +} + +// Function to find the last element +// of the Queue +template +X Queue::back() +{ + if (empty()) { + cout << "Queue underflow" + << endl; + abort(); + } + return arr[backIndex]; +} + +// Function to insert the element +// to the rear end of the queue +template +void Queue::push(X x) +{ + if (full()) { + + // If the queue is full, then + // double the capacity + capacityVar = capacityVar * 2; + + // Initialize new array of + // double size + X* temp = new X[capacityVar]; + + // Copy the elements of the + // previous array in the order of the queue + for (int i = 0, j= frontIndex; i < sizeVar; i++){ + temp[i] = arr[j]; + j = (j+1) % sizeVar; + } + // update the front and rear indices in the new array + frontIndex = 0; + backIndex = sizeVar -1; + + // Deallocate the memory + // of previous array + delete[] arr; + arr = temp; + } + + // If size is zero + if (empty()) { + + frontIndex = backIndex = 0; + arr[backIndex] = x; + sizeVar++; + return; + } + + // Increment the backIndex + backIndex = (backIndex + 1) % capacityVar; + arr[backIndex] = x; + sizeVar++; + + return; +} + +// Function to pop an element from +// front end of the queue +template +void Queue::pop() +{ + // If queue is empty + if (empty()) { + cout << "Queue underflow" + << endl; + abort(); + } + + // If there is only one character + if (frontIndex == backIndex) { + + // Mark Queue as empty + // and decrement sizeVar + frontIndex = backIndex = -1; + sizeVar--; + return; + } + + // Increment frontIndex cyclically + // using modulo arithmetic + frontIndex = (frontIndex + 1) % capacityVar; + sizeVar--; + + return; +} + +// Driver Code +int main() +{ + // Queue initialization + Queue q; + + // Iterate the range [1, 100] + for (int i = 1; i < 5; i++) + q.push(i); + + // Print the current capacity + cout << "Current capacity " + << q.capacity() << endl; + + // Print current size + cout << "Current size " + << q.size() << endl; + + // Print front elements of queue + cout << "Front element " + << q.front() << endl; + + // Print last element of the queue + cout << "Rear element " + << q.back() << endl; + + cout << endl; + + cout << "Pop an element" << endl; + + // Pop an element from the queue + q.pop(); + + cout << "Pop an element" << endl; + + // Pop an element from the queue + q.pop(); + + cout << endl; + + // Print the current capacity + cout << "Current capacity " + << q.capacity() << endl; + + // Print current size + cout << "Current size " + << q.size() << endl; + + // Print front elements of queue + cout << "Front element " + << q.front() << endl; + + // Print last element of the queue + cout << "Rear element " + << q.back() << endl; + + cout << endl; + cout << "Push element 5" << endl; + cout << "Push element 6" << endl; + + + q.push(5); + q.push(6); + cout << endl; + + // Print the current capacity + cout << "Current capacity " + << q.capacity() << endl; + + // Print current size + cout << "Current size " + << q.size() << endl; + + // Print front elements of queue + cout << "Front element " + << q.front() << endl; + + // Print last element of the queue + cout << "Rear element " + << q.back() << endl; + + cout << endl; + cout << "Push element 7" << endl; + q.push(7); + + cout << endl; + + // Print the current capacity + cout << "Current capacity " + << q.capacity() << endl; + + // Print current size + cout << "Current size " + << q.size() << endl; + + // Print front elements of queue + cout << "Front element " + << q.front() << endl; + + // Print last element of the queue + cout << "Rear element " + << q.back() << endl; + + return 0; +} From 2293aaa69f94fa1b62e42064158a2a970f2d9681 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sat, 8 Oct 2022 23:40:23 +0530 Subject: [PATCH 4/9] Create hash maps implementation --- hash maps implementation | 171 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 171 insertions(+) create mode 100644 hash maps implementation diff --git a/hash maps implementation b/hash maps implementation new file mode 100644 index 0000000..d910b0d --- /dev/null +++ b/hash maps implementation @@ -0,0 +1,171 @@ +#include +using namespace std; + +// template for generic type +template + +// Hashnode class +class HashNode { +public: + V value; + K key; + + // Constructor of hashnode + HashNode(K key, V value) + { + this->value = value; + this->key = key; + } +}; + +// template for generic type +template + +// Our own Hashmap class +class HashMap { + // hash element array + HashNode** arr; + int capacity; + // current size + int size; + // dummy node + HashNode* dummy; + +public: + HashMap() + { + // Initial capacity of hash array + capacity = 20; + size = 0; + arr = new HashNode*[capacity]; + + // Initialise all elements of array as NULL + for (int i = 0; i < capacity; i++) + arr[i] = NULL; + + // dummy node with value and key -1 + dummy = new HashNode(-1, -1); + } + // This implements hash function to find index + // for a key + int hashCode(K key) + { + return key % capacity; + } + + // Function to add key value pair + void insertNode(K key, V value) + { + HashNode* temp = new HashNode(key, value); + + // Apply hash function to find index for given key + int hashIndex = hashCode(key); + + // find next free space + while (arr[hashIndex] != NULL + && arr[hashIndex]->key != key + && arr[hashIndex]->key != -1) { + hashIndex++; + hashIndex %= capacity; + } + + // if new node to be inserted + // increase the current size + if (arr[hashIndex] == NULL + || arr[hashIndex]->key == -1) + size++; + arr[hashIndex] = temp; + } + + // Function to delete a key value pair + V deleteNode(int key) + { + // Apply hash function + // to find index for given key + int hashIndex = hashCode(key); + + // finding the node with given key + while (arr[hashIndex] != NULL) { + // if node found + if (arr[hashIndex]->key == key) { + HashNode* temp = arr[hashIndex]; + + // Insert dummy node here for further use + arr[hashIndex] = dummy; + + // Reduce size + size--; + return temp->value; + } + hashIndex++; + hashIndex %= capacity; + } + + // If not found return null + return NULL; + } + + // Function to search the value for a given key + V get(int key) + { + // Apply hash function to find index for given key + int hashIndex = hashCode(key); + int counter = 0; + + // finding the node with given key + while (arr[hashIndex] != NULL) { // int counter =0; // BUG! + + if (counter++ > capacity) // to avoid infinite loop + return NULL; + + // if node found return its value + if (arr[hashIndex]->key == key) + return arr[hashIndex]->value; + hashIndex++; + hashIndex %= capacity; + } + + // If not found return null + return NULL; + } + + // Return current size + int sizeofMap() + { + return size; + } + + // Return true if size is 0 + bool isEmpty() + { + return size == 0; + } + + // Function to display the stored key value pairs + void display() + { + for (int i = 0; i < capacity; i++) { + if (arr[i] != NULL && arr[i]->key != -1) + cout << "key = " << arr[i]->key + << " value = " + << arr[i]->value << endl; + } + } +}; + +// Driver method to test map class +int main() +{ + HashMap* h = new HashMap; + h->insertNode(1, 1); + h->insertNode(2, 2); + h->insertNode(2, 3); + h->display(); + cout << h->sizeofMap() << endl; + cout << h->deleteNode(2) << endl; + cout << h->sizeofMap() << endl; + cout << h->isEmpty() << endl; + cout << h->get(2); + + return 0; +} From cd34451284bddd0e04563f94073c86fdb702d1f8 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sat, 8 Oct 2022 23:41:35 +0530 Subject: [PATCH 5/9] Create hashing with chaining --- hashing with chaining | 88 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 hashing with chaining diff --git a/hashing with chaining b/hashing with chaining new file mode 100644 index 0000000..36a953a --- /dev/null +++ b/hashing with chaining @@ -0,0 +1,88 @@ +// CPP program to implement hashing with chaining +#include +using namespace std; + +class Hash +{ + int BUCKET; // No. of buckets + + // Pointer to an array containing buckets + list *table; +public: + Hash(int V); // Constructor + + // inserts a key into hash table + void insertItem(int x); + + // deletes a key from hash table + void deleteItem(int key); + + // hash function to map values to key + int hashFunction(int x) { + return (x % BUCKET); + } + + void displayHash(); +}; + +Hash::Hash(int b) +{ + this->BUCKET = b; + table = new list[BUCKET]; +} + +void Hash::insertItem(int key) +{ + int index = hashFunction(key); + table[index].push_back(key); +} + +void Hash::deleteItem(int key) +{ +// get the hash index of key +int index = hashFunction(key); + +// find the key in (index)th list +list :: iterator i; +for (i = table[index].begin(); + i != table[index].end(); i++) { + if (*i == key) + break; +} + +// if key is found in hash table, remove it +if (i != table[index].end()) + table[index].erase(i); +} + +// function to display hash table +void Hash::displayHash() { +for (int i = 0; i < BUCKET; i++) { + cout << i; + for (auto x : table[i]) + cout << " --> " << x; + cout << endl; +} +} + +// Driver program +int main() +{ +// array that contains keys to be mapped +int a[] = {15, 11, 27, 8, 12}; +int n = sizeof(a)/sizeof(a[0]); + +// insert the keys into the hash table +Hash h(7); // 7 is count of buckets in + // hash table +for (int i = 0; i < n; i++) + h.insertItem(a[i]); + +// delete 12 from hash table +h.deleteItem(12); + +// display the Hash table +h.displayHash(); + +return 0; +} From 5c8af3cef4815e8fdb79f7c9dcc75376c24946b1 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:38:39 +0530 Subject: [PATCH 6/9] Create Write a program to reverse an array or string --- Write a program to reverse an array or string | 46 +++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Write a program to reverse an array or string diff --git a/Write a program to reverse an array or string b/Write a program to reverse an array or string new file mode 100644 index 0000000..e038ccf --- /dev/null +++ b/Write a program to reverse an array or string @@ -0,0 +1,46 @@ +// Iterative C++ program to reverse an array +#include +using namespace std; + +/* Function to reverse arr[] from start to end*/ +void rvereseArray(int arr[], int start, int end) +{ + while (start < end) + { + int temp = arr[start]; + arr[start] = arr[end]; + arr[end] = temp; + start++; + end--; + } +} + +/* Utility function to print an array */ +void printArray(int arr[], int size) +{ +for (int i = 0; i < size; i++) +cout << arr[i] << " "; + +cout << endl; +} + +/* Driver function to test above functions */ +int main() +{ + int arr[] = {1, 2, 3, 4, 5, 6}; + + int n = sizeof(arr) / sizeof(arr[0]); + + // To print original array + printArray(arr, n); + + // Function calling + rvereseArray(arr, 0, n-1); + + cout << "Reversed array is" << endl; + + // To print the Reversed array + printArray(arr, n); + + return 0; +} From f68e468c5f453c0efe8e81eab25ccf19e8365e7e Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:39:40 +0530 Subject: [PATCH 7/9] Create program to sort an array in ascending order --- program to sort an array in ascending order | 55 +++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 program to sort an array in ascending order diff --git a/program to sort an array in ascending order b/program to sort an array in ascending order new file mode 100644 index 0000000..f3b9c3c --- /dev/null +++ b/program to sort an array in ascending order @@ -0,0 +1,55 @@ +// C program to sort the array in an +// ascending order using selection sort +#include + +void swap(int* xp, int* yp) +{ + int temp = *xp; + *xp = *yp; + *yp = temp; +} + +// Function to perform Selection Sort +void selectionSort(int arr[], int n) +{ + int i, j, min_idx; + + // One by one move boundary of + // unsorted subarray + for (i = 0; i < n - 1; i++) { + // Find the minimum element in + // unsorted array + min_idx = i; + for (j = i + 1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element + // with the first element + swap(&arr[min_idx], &arr[i]); + } +} + +// Function to print an array +void printArray(int arr[], int size) +{ + int i; + for (i = 0; i < size; i++) + printf("%d ", arr[i]); + printf("\n"); +} + +// Driver code +int main() +{ + int arr[] = { 0, 23, 14, 12, 9 }; + int n = sizeof(arr) / sizeof(arr[0]); + printf("Original array: \n"); + printArray(arr, n); + + selectionSort(arr, n); + printf("\nSorted array in Ascending order: \n"); + printArray(arr, n); + + return 0; +} From d806524c475cd5d788d8fc7db4148d3ebaea9851 Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:40:35 +0530 Subject: [PATCH 8/9] Create Sort an array of 0s, 1s and 2s --- Sort an array of 0s, 1s and 2s | 59 ++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 Sort an array of 0s, 1s and 2s diff --git a/Sort an array of 0s, 1s and 2s b/Sort an array of 0s, 1s and 2s new file mode 100644 index 0000000..65fbc42 --- /dev/null +++ b/Sort an array of 0s, 1s and 2s @@ -0,0 +1,59 @@ +// C++ program to sort an array +// with 0, 1 and 2 in a single pass +#include +using namespace std; + +// Function to sort the input array, +// the array is assumed +// to have values in {0, 1, 2} +void sort012(int a[], int arr_size) +{ + int lo = 0; + int hi = arr_size - 1; + int mid = 0; + + // Iterate till all the elements + // are sorted + while (mid <= hi) { + switch (a[mid]) { + + // If the element is 0 + case 0: + swap(a[lo++], a[mid++]); + break; + + // If the element is 1 . + case 1: + mid++; + break; + + // If the element is 2 + case 2: + swap(a[mid], a[hi--]); + break; + } + } +} + +// Function to print array arr[] +void printArray(int arr[], int arr_size) +{ + // Iterate and print every element + for (int i = 0; i < arr_size; i++) + cout << arr[i] << " "; +} + +// Driver Code +int main() +{ + int arr[] = { 0, 1, 1, 0, 1, 2, 1, 2, 0, 0, 0, 1 }; + int n = sizeof(arr) / sizeof(arr[0]); + + sort012(arr, n); + + printArray(arr, n); + + return 0; +} + +// This code is contributed by Shivi_Aggarwal From 8a36b89e62a0d1b7df39ba8646f028c483cac5ce Mon Sep 17 00:00:00 2001 From: garud-dwar <115369078+garud-dwar@users.noreply.github.com> Date: Sun, 8 Oct 2023 08:41:22 +0530 Subject: [PATCH 9/9] Create Find Subarray with given sum --- Find Subarray with given sum | 48 ++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 Find Subarray with given sum diff --git a/Find Subarray with given sum b/Find Subarray with given sum new file mode 100644 index 0000000..cddee7d --- /dev/null +++ b/Find Subarray with given sum @@ -0,0 +1,48 @@ +/* A simple program to print subarray +with sum as given sum */ +#include +using namespace std; + +/* Returns true if the there is a subarray +of arr[] with sum equal to 'sum' otherwise +returns false. Also, prints the result */ +void subArraySum(int arr[], int n, int sum) +{ + + // Pick a starting point + for (int i = 0; i < n; i++) { + int currentSum = arr[i]; + + if (currentSum == sum) { + cout << "Sum found at indexes " << i << endl; + return; + } + else { + // Try all subarrays starting with 'i' + for (int j = i + 1; j < n; j++) { + currentSum += arr[j]; + + if (currentSum == sum) { + cout << "Sum found between indexes " + << i << " and " << j << endl; + return; + } + } + } + } + cout << "No subarray found"; + return; +} + +// Driver Code +int main() +{ + int arr[] = { 15, 2, 4, 8, 9, 5, 10, 23 }; + int n = sizeof(arr) / sizeof(arr[0]); + int sum = 23; + subArraySum(arr, n, sum); + return 0; +} + +// This code is contributed +// by rathbhupendra