├── .github └── workflows │ └── main.yml ├── CONTRIBUTING.md ├── README.md ├── c ├── AVLInsDel.c ├── BFSandDFS.c ├── BSTAllOperations.c ├── Floyd's-Hare-And-Turtle.c ├── HeapSort.c ├── LinkedList.c ├── Stack.c ├── bubbleSort.c ├── selectionSort.c └── tower-of-hanoi.c ├── cpp ├── BFS.cpp ├── BubbleSort.cpp ├── ExponentialSearch.cpp ├── FloydWarshall.cpp ├── Hashmap.cpp ├── JumpSearch.cpp ├── MergeSort.cpp ├── Number_of_island ├── SmallestElementBST.cpp ├── TreeTraversals.cpp ├── addMatrix.cpp ├── armstrongNumber.cpp ├── insertion_in_linkedlist.cpp ├── palindromeSeries.cpp ├── selectionSort.cpp └── selectionsSort.cpp ├── csharp ├── BinarySearch.cs ├── BubbleSort.cs └── Selectionsort.cs ├── golang ├── ArmstrongNumber.go ├── BinarySearch.go ├── InsertionSort.go ├── MergeSort.go ├── Palindrome.go ├── PascalsTr.go ├── Readme.md ├── SelectionSort.go └── quickSort.go ├── java ├── BinarySearch.java ├── BubbleSort.java ├── InsertionSort.java ├── LinearSearch.java ├── MergeSort.java ├── SelectionSort.java ├── Stack.java ├── StackDemo.java ├── quickSort.java └── shellSort.java ├── javascript ├── BinarySearch.js ├── BubbleSort.js ├── InsertionSort.js ├── LinearSearch.js ├── LinkedList.js ├── MergeSort.js ├── SelectionSort.js └── Stack.js ├── python ├── BinarySearch.py ├── BubbleSort.py ├── CountingSort.py ├── HeapSort.py ├── InsertionSort.py ├── LinearSearch.py ├── LinkedList.py ├── MergeSort.py ├── NumberSort.py ├── breadthFirstSearch.py ├── bucketSort.py ├── depthFirstSearch.py └── selectionSort.py └── rust ├── BinarySearch.rs ├── BubbleSort.rs ├── Queue.rs └── Stack.rs /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Update CONTRIBUTING.md 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | 7 | # A workflow run is made up of one or more jobs that can run sequentially or in parallel 8 | jobs: 9 | # This workflow contains a single job called "build" 10 | build: 11 | # The type of runner that the job will run on 12 | runs-on: ubuntu-latest 13 | 14 | # Steps represent a sequence of tasks that will be executed as part of the job 15 | steps: 16 | # Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it 17 | - uses: actions/checkout@v2 18 | 19 | - name: Install jq 20 | run: sudo apt-get install jq 21 | 22 | - name: Update languages in CONTRIBUTING. 23 | run: | 24 | blockStart="" 25 | blockEnd="" 26 | 27 | flag="" 28 | 29 | while IFS= read -r line; do 30 | if [[ $flag == "" ]]; then 31 | echo $line >> tmp.md 32 | elif [[ $flag == "start" ]]; then 33 | languages=`curl -sH "Accept: application/vnd.github.v3+json" https://api.github.com/repos/anuragdevon/Data-Structures/languages | jq -r 'keys[]'` 34 | count=1 35 | for language in $languages; do 36 | echo "$count. $language" >> tmp.md 37 | ((count++)) 38 | done 39 | flag="end" 40 | elif [[ $flag == "end" && $line == $blockEnd ]]; then 41 | echo $line >> tmp.md 42 | flag="" 43 | fi 44 | 45 | if [[ $line == $blockStart ]]; then 46 | flag="start" 47 | fi 48 | done < CONTRIBUTING.md 49 | 50 | rm CONTRIBUTING.md 51 | mv tmp.md CONTRIBUTING.md 52 | 53 | - name: Commit report 54 | run: | 55 | git config --global user.name 'GitHub Actions Bot' 56 | git config --global user.email '' 57 | git commit -am "Update CONTRIBUTING.md" 58 | git push 59 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Data structures and Algorithms 2 | > Languages used here: 3 | 4 | 1. C 5 | 2. C# 6 | 3. C++ 7 | 4. Go 8 | 5. Java 9 | 6. JavaScript 10 | 7. Python 11 | 8. Rust 12 | 13 | 14 | *Good contributions are always welcome :)* 15 | > Procedure for contributing: 16 | - `Fork` this repository 17 | - `Clone` it to local desktop 18 | - Make changes to in local environment 19 | - `Commit` and `push` the new branch created 20 | - Apply for `pull request` 21 | 22 | # Algorithms and languages used 23 | 24 | 25 | Algorithm\\Language | C++ | Golang | Java | JavaScript | Python | Rust | C# 26 | ------------ | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- 27 | Armstrong Number | X | O | X | X | X | X | X 28 | BFS | X | X | X | X | X | O | X 29 | Binary Search | X | O | O | O | O | O | O 30 | BST(kth smallest) | O | X | X | X | X | X | X 31 | Bubble Sort | O | X | O | O | O | O | O 32 | Counting Sort | X | X | X | X | O | X | X 33 | DFS | X | X | X | X | X | O | X 34 | Exponential Search | O | X | X | X | X | X | X 35 | Hashmap | O | X | X | X | X | X | X 36 | Heap Sort | X | X | X | X | O | X | X 37 | Insertion Sort | X | O | O | O | O | X | X 38 | Jump Search | O | X | X | X | X | X | X 39 | Linear Search | X | X | O | O | O | X | X 40 | Linked List | X | O | X | O | O | X | X 41 | Merge Sort | O | O | X | O | O | X | X 42 | Number Sort | X | O | X | X | O | X | X 43 | Pascals Triangle | X | O | X | X | X | X | X 44 | Queue | X | X | X | X | X | O | X 45 | Selection Sort | O | O | O | O | O | X | O 46 | Stack | X | X | O | O | X | O | X 47 | StackDemo | X | X | O | X | X | X | X 48 | Tree Transversal | O | X | X | X | X | X | X 49 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structures 2 | Data structures and Algorithmic codes 3 | - Add the codes which are easy to understand and are applicable 4 | - try to add simplified code for better understanding 5 | -------------------------------------------------------------------------------- /c/AVLInsDel.c: -------------------------------------------------------------------------------- 1 | // C program to delete a node from AVL Tree 2 | #include 3 | #include 4 | 5 | // AVL node 6 | struct Node 7 | { 8 | int key; 9 | struct Node *left; 10 | struct Node *right; 11 | int height; 12 | }; 13 | 14 | // function for maximum returning 15 | int max(int a, int b) 16 | { 17 | return (a > b)? a : b; 18 | } 19 | 20 | // for calculating the tree node 21 | int height(struct Node *N) 22 | { 23 | if (N == NULL) 24 | return 0; 25 | return N->height; 26 | } 27 | 28 | // functionm to create a new node 29 | struct Node* newNode(int key) 30 | { 31 | struct Node* node = (struct Node*) 32 | malloc(sizeof(struct Node)); 33 | node->key = key; 34 | node->left = NULL; 35 | node->right = NULL; 36 | node->height = 1; // new node is initially added at leaf 37 | return(node); 38 | } 39 | 40 | // function to rotate tree right 41 | struct Node *rightRotate(struct Node *y) 42 | { 43 | struct Node *x = y->left; 44 | struct Node *T2 = x->right; 45 | 46 | // Perform rotation 47 | x->right = y; 48 | y->left = T2; 49 | 50 | // Update heights 51 | y->height = max(height(y->left), height(y->right))+1; 52 | x->height = max(height(x->left), height(x->right))+1; 53 | 54 | // Return new root 55 | return x; 56 | } 57 | 58 | // for left rotate 59 | struct Node *leftRotate(struct Node *x) 60 | { 61 | struct Node *y = x->right; 62 | struct Node *T2 = y->left; 63 | 64 | // Perform rotation 65 | y->left = x; 66 | x->right = T2; 67 | 68 | // Update heights 69 | x->height = max(height(x->left), height(x->right))+1; 70 | y->height = max(height(y->left), height(y->right))+1; 71 | 72 | // Return new root 73 | return y; 74 | } 75 | 76 | // getting the balance nodfe 77 | int Balance(struct Node *N) 78 | { 79 | if (N == NULL) 80 | return 0; 81 | return height(N->left) - height(N->right); 82 | } 83 | 84 | struct Node* insert(struct Node* node, int key) 85 | { 86 | if (node == NULL) 87 | return(newNode(key)); 88 | 89 | if (key < node->key) 90 | node->left = insert(node->left, key); 91 | else if (key > node->key) 92 | node->right = insert(node->right, key); 93 | else 94 | return node; 95 | 96 | node->height = 1 + max(height(node->left), 97 | height(node->right)); 98 | 99 | int balance = Balance(node); 100 | 101 | // If this node becomes unbalanced, then there are 4 cases 102 | 103 | // LL 104 | if (balance > 1 && key < node->left->key) 105 | return rightRotate(node); 106 | 107 | // RR 108 | if (balance < -1 && key > node->right->key) 109 | return leftRotate(node); 110 | 111 | // LR 112 | if (balance > 1 && key > node->left->key) 113 | { 114 | node->left = leftRotate(node->left); 115 | return rightRotate(node); 116 | } 117 | 118 | // RL 119 | if (balance < -1 && key < node->right->key) 120 | { 121 | node->right = rightRotate(node->right); 122 | return leftRotate(node); 123 | } 124 | return node; 125 | } 126 | 127 | // to calculate the minimum value of node 128 | struct Node * minValueNode(struct Node* node) 129 | { 130 | struct Node* current = node; 131 | 132 | /* loop down to find the leftmost leaf */ 133 | while (current->left != NULL) 134 | current = current->left; 135 | 136 | return current; 137 | } 138 | 139 | // delete function for all 3 cases 140 | struct Node* DeleteNode(struct Node* root, int key) 141 | { 142 | // STEP 1: PERFORM STANDARD BST DELETE 143 | 144 | if (root == NULL) 145 | return root; 146 | 147 | if ( key < root->key ) 148 | root->left = DeleteNode(root->left, key); 149 | 150 | 151 | else if( key > root->key ) 152 | root->right = DeleteNode(root->right, key); 153 | 154 | else 155 | { 156 | // node with only one child or no child 157 | if( (root->left == NULL) || (root->right == NULL) ) 158 | { 159 | struct Node *temp = root->left ? root->left : 160 | root->right; 161 | 162 | // No child case 163 | if (temp == NULL) 164 | { 165 | temp = root; 166 | root = NULL; 167 | } 168 | else 169 | *root = *temp; 170 | free(temp); 171 | } 172 | else 173 | { 174 | struct Node* temp = minValueNode(root->right); 175 | 176 | // Copy the inorder successor's data to this node 177 | root->key = temp->key; 178 | 179 | // Delete the inorder successor 180 | root->right = DeleteNode(root->right, temp->key); 181 | } 182 | } 183 | 184 | // If the tree had only one node then return 185 | if (root == NULL) 186 | return root; 187 | 188 | // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE 189 | root->height = 1 + max(height(root->left), 190 | height(root->right)); 191 | 192 | int balance = Balance(root); 193 | 194 | if (balance > 1 && Balance(root->left) >= 0) 195 | return rightRotate(root); 196 | 197 | // Left Right Case 198 | if (balance > 1 && Balance(root->left) < 0) 199 | { 200 | root->left = leftRotate(root->left); 201 | return rightRotate(root); 202 | } 203 | 204 | // Right Right Case 205 | if (balance < -1 && Balance(root->right) <= 0) 206 | return leftRotate(root); 207 | 208 | // Right Left Case 209 | if (balance < -1 && Balance(root->right) > 0) 210 | { 211 | root->right = rightRotate(root->right); 212 | return leftRotate(root); 213 | } 214 | 215 | return root; 216 | } 217 | 218 | // for printing the Predorer traversal 219 | void Predorer(struct Node *root) 220 | { 221 | if(root != NULL) 222 | { 223 | printf("%d ", root->key); 224 | Predorer(root->left); 225 | Predorer(root->right); 226 | } 227 | } 228 | 229 | // main function begins here 230 | int main() 231 | { 232 | struct Node *root = NULL; 233 | int data; // the value to be inserted 234 | printf("\nAVL TREE\n\n"); 235 | printf("Enter the value for contructing the binary tree...\n"); 236 | while(1) 237 | { 238 | printf("Enter the number to be inserted: "); 239 | scanf("%d",&data); 240 | insert(root,data); 241 | printf("\nTask completed!\n"); 242 | printf("Due you want to continue(y-1/n-0): "); 243 | scanf("%d",&data); 244 | if(data == 0) 245 | break; 246 | } 247 | 248 | printf("The final Tree after AVL conversion(presorder traversal): "); 249 | Predorer(root); 250 | 251 | while(1) 252 | { 253 | printf("Enter the number to be Deleted: "); 254 | scanf("%d",&data); 255 | DeleteNode(root, data); 256 | printf("\nTask completed!\n"); 257 | printf("Due you want to continue(y-1/n-0): "); 258 | scanf("%d",&data); 259 | 260 | printf("The status of tree after deletion(Predorer traversal): \n"); 261 | Predorer(root); 262 | if(data == 0) 263 | break; 264 | } 265 | printf("\nExiting...\n"); 266 | return 0; // successfull completion 267 | } 268 | -------------------------------------------------------------------------------- /c/BFSandDFS.c: -------------------------------------------------------------------------------- 1 | // DFS algorithm in C 2 | 3 | // header files 4 | #include 5 | #include 6 | // for bfs queue 7 | #define SIZE 100 8 | 9 | // for the structure queue 10 | struct queue { 11 | int items[SIZE]; 12 | int front; 13 | int rear; 14 | }; 15 | 16 | // structure for node 17 | struct node 18 | { 19 | int vertex; 20 | struct node* next; 21 | }; 22 | 23 | struct node* NewNode(int v); 24 | 25 | // structure for the graph 26 | struct Graph 27 | { 28 | int numVertices; 29 | int* visited; 30 | struct node** adjancent; 31 | }; 32 | 33 | // Create a queue 34 | struct queue* NewQueu() { 35 | struct queue* q = malloc(sizeof(struct queue)); 36 | q->front = -1; 37 | q->rear = -1; 38 | return q; 39 | } 40 | 41 | // Check if the queue is empty 42 | int isEmpty(struct queue* q) { 43 | if (q->rear == -1) 44 | return 1; 45 | else 46 | return 0; 47 | } 48 | 49 | // Adding elements into queue 50 | void Enqueue(struct queue* q, int value) { 51 | if (q->rear == SIZE - 1) 52 | printf("\nOh!, the queue is full\n"); 53 | else { 54 | if (q->front == -1) 55 | q->front = 0; 56 | q->rear++; 57 | q->items[q->rear] = value; 58 | } 59 | } 60 | 61 | // Removing elements from queue 62 | int Dequeue(struct queue* q) { 63 | int item; 64 | if (isEmpty(q)) { 65 | printf("\nOops!, the queue is empty\n"); 66 | item = -1; 67 | } else { 68 | item = q->items[q->front]; 69 | q->front++; 70 | if (q->front > q->rear) { 71 | printf("Queue us being changed\n"); 72 | q->front = q->rear = -1; 73 | } 74 | } 75 | return item; 76 | } 77 | 78 | // Print the queue 79 | void DisplayQueue(struct queue* q) { 80 | int i = q->front; 81 | 82 | if (isEmpty(q)) { 83 | printf("\nOops!, the queue is empty\n"); 84 | } else { 85 | printf("\nQueue: \n"); 86 | for (i = q->front; i < q->rear + 1; i++) { 87 | printf("%d ", q->items[i]); 88 | } 89 | } 90 | } 91 | 92 | // BFS algorithm 93 | void bfs(struct Graph* graph, int startVertex) { 94 | struct queue* q = NewQueu(); 95 | 96 | graph->visited[startVertex] = 1; 97 | Enqueue(q, startVertex); 98 | 99 | while (!isEmpty(q)) { 100 | DisplayQueue(q); 101 | int currentVertex = Dequeue(q); 102 | printf("Vertex visited %d\n", currentVertex); 103 | 104 | struct node* temp = graph->adjancent[currentVertex]; 105 | 106 | while (temp) { 107 | int adjVertex = temp->vertex; 108 | 109 | if (graph->visited[adjVertex] == 0) { 110 | graph->visited[adjVertex] = 1; 111 | Enqueue(q, adjVertex); 112 | } 113 | temp = temp->next; 114 | } 115 | } 116 | } 117 | 118 | // Build a new graph 119 | struct Graph* BuildGraph(int vertices) { 120 | struct Graph* graph = malloc(sizeof(struct Graph)); 121 | graph->numVertices = vertices; 122 | 123 | graph->adjancent = malloc(vertices * sizeof(struct node*)); 124 | 125 | graph->visited = malloc(vertices * sizeof(int)); 126 | 127 | int i; 128 | for (i = 0; i < vertices; i++) { 129 | graph->adjancent[i] = NULL; 130 | graph->visited[i] = 0; 131 | } 132 | return graph; 133 | } 134 | 135 | // This function will simply add a new edge 136 | void NewEdge(struct Graph* graph, int src, int dest) { 137 | // Add edge from src to dest 138 | struct node* newNode = NewNode(dest); 139 | newNode->next = graph->adjancent[src]; 140 | graph->adjancent[src] = newNode; 141 | 142 | // Add edge from dest to src 143 | newNode = NewNode(src); 144 | newNode->next = graph->adjancent[dest]; 145 | graph->adjancent[dest] = newNode; 146 | } 147 | 148 | // DFS algo 149 | void DFS(struct Graph* graph, int vertex) { 150 | struct node* adjList = graph->adjancent[vertex]; 151 | struct node* temp = adjList; 152 | 153 | graph->visited[vertex] = 1; 154 | printf("It is Visited %d \n", vertex); 155 | 156 | while (temp != NULL) { 157 | int connectedVertex = temp->vertex; 158 | 159 | if (graph->visited[connectedVertex] == 0) { 160 | DFS(graph, connectedVertex); 161 | } 162 | temp = temp->next; 163 | } 164 | } 165 | 166 | // Create a node 167 | struct node* NewNode(int v) { 168 | struct node* newNode = malloc(sizeof(struct node)); 169 | newNode->vertex = v; 170 | newNode->next = NULL; 171 | return newNode; 172 | } 173 | 174 | // Print the graph 175 | void Display(struct Graph* graph) { 176 | int v; 177 | for (v = 0; v < graph->numVertices; v++) { 178 | struct node* temp = graph->adjancent[v]; 179 | printf("\nAdjacent to %d", v); 180 | while (temp) { 181 | printf("%d -> ", temp->vertex); 182 | temp = temp->next; 183 | } 184 | printf("\n"); 185 | } 186 | } 187 | 188 | // main function begins here 189 | int main() 190 | { 191 | printf("\nGRAPHS\n\n"); 192 | int Vertices, Source, Destination, i = 0; 193 | 194 | printf("Enter the first Vertex: "); 195 | scanf("%d",&Vertices); 196 | 197 | // to store the source and destination 198 | // creating a graph 199 | struct Graph* NewGraph = BuildGraph(Vertices); 200 | printf("Enter the edge details...\n"); 201 | while(1) 202 | { 203 | printf("Enter the Source vertex: "); 204 | scanf("%d",&Source); 205 | printf("Enter the destination vertices: "); 206 | scanf("%d",&Destination); 207 | NewEdge(NewGraph, Source, Vertices); 208 | 209 | printf("Do you want to continue(y(1)/n(0)): "); 210 | scanf("%d",&i); 211 | if(i == 0) 212 | { 213 | i = Source; // for getting a random vertex so as to start the dfs execution 214 | break; 215 | } 216 | } 217 | 218 | // diplaying the original graph 219 | printf("the original graph is: \n"); 220 | Display(NewGraph); 221 | 222 | // The DFS form 223 | printf("The DFS is: \n"); 224 | DFS(NewGraph, i); 225 | 226 | // The DFS form 227 | printf("The BFS is: \n"); 228 | bfs(NewGraph, i); 229 | 230 | return 0; 231 | 232 | } -------------------------------------------------------------------------------- /c/BSTAllOperations.c: -------------------------------------------------------------------------------- 1 | // program for BST insertion, transversal, min, max, searching and deletion 2 | 3 | #include 4 | #include 5 | 6 | struct node{ 7 | int info; 8 | struct node *left, *right, *head; 9 | }*pred = NULL, *succ = NULL; 10 | 11 | // function for creation of new node 12 | struct node *NewNode(int item){ 13 | struct node *temp = (struct node *)malloc(sizeof(struct node)); // will create a struct node type UD variable temp 14 | temp -> info = item; // data storage 15 | temp -> left = temp -> right = NULL; // assign the leafs to NULL 16 | 17 | return temp; // will return the creted node 18 | } 19 | 20 | /* --Listing out all the displat functions 21 | -----------------------------------------*/ 22 | 23 | // function for inorder transversal 24 | void Inorder(struct node *root){ 25 | if (root != NULL){ 26 | Inorder(root -> left); 27 | printf("%d -> ", root -> info); 28 | Inorder(root -> right); 29 | } 30 | } 31 | 32 | // function for preorder transversal 33 | void Preorder(struct node *root){ 34 | // base case 35 | if (root == NULL) 36 | return; 37 | // printing the leaf 38 | printf("%d -> ", root -> info); 39 | // moving to left subtree 40 | Preorder(root -> left); 41 | // moving to right subtree 42 | Preorder(root -> right); 43 | } 44 | 45 | // function to postorder transversal 46 | void Postorder(struct node *root){ 47 | // base case 48 | if(root == NULL) 49 | return; 50 | // moving to left subtree 51 | Postorder(root -> left); 52 | // moving to right subtree 53 | Postorder(root -> right); 54 | // printing the leaf 55 | printf("%d -> ", root -> info); 56 | } 57 | 58 | /*------------------------------------- 59 | all displpay functions completes here */ 60 | 61 | // function for insertion of new node 62 | struct node* Insert(struct node* node, int info){ 63 | // if the tree is empty 64 | if(node == NULL) 65 | return NewNode(info); 66 | // for getting to bottom leaves 67 | if (info < node -> info) 68 | node -> left = Insert(node -> left, info); 69 | else 70 | node -> right = Insert(node -> right, info); 71 | 72 | return node; 73 | } 74 | 75 | // this function will give the minimum value in the given tree 76 | struct node* MinVal(struct node* node){ 77 | struct node* current = node; 78 | while(current && current -> left != NULL) // finding the leftmost leaf 79 | current = current -> left; 80 | 81 | return current; 82 | } 83 | 84 | // function to delete the node 85 | struct node* Delete(struct node* root, int info){ 86 | // for the base case 87 | if (root == NULL) 88 | return root; 89 | // if the node is smaller, will lie on left subtree 90 | if(info < root -> info) 91 | root -> left = Delete(root -> left, info); 92 | // if the node is greater, it will lie on the right subtree 93 | else if(info > root -> info) 94 | root -> right = Delete(root -> right, info); 95 | // if node is same as root key 96 | else{ 97 | // now here applying all the conditions 98 | // root with only one child or no child 99 | if(root -> left == NULL){ 100 | struct node *temp = root -> right; 101 | free(root); 102 | return temp; 103 | } 104 | else if(root -> right == NULL){ 105 | struct node *temp = root -> left; 106 | free(root); 107 | return temp; 108 | } 109 | 110 | // for node with 2 children 111 | struct node* temp = MinVal(root -> right); 112 | 113 | // replicating the inorder successor's content to thre node 114 | root -> info = temp -> info; 115 | 116 | // deleting the successor 117 | root -> right = Delete(root -> right, temp -> info); 118 | } 119 | return root; 120 | } 121 | 122 | // function to get the maximum element 123 | int Maximum(struct node* root){ 124 | if(root -> right == NULL) 125 | return root -> info; 126 | return Maximum(root -> right); // for recursive call to reach the right most leaf 127 | } 128 | 129 | // function to get the minimum element 130 | int Minimum(struct node* root){ 131 | if(root -> left == NULL) 132 | return root -> info; 133 | return Minimum(root -> left); 134 | } 135 | 136 | // function for searching the element 137 | int Search(struct node* root, int x){ 138 | // base case 139 | if(root == NULL) 140 | return -1; 141 | else if(root -> info == x) 142 | return 1; 143 | else if(x > root -> info == x) 144 | return Search(root -> right, x); 145 | else 146 | return Search(root -> left, x); 147 | 148 | } 149 | 150 | // combined function to find the both successor and predecessor 151 | void FindPS(struct node* root, int op){ 152 | // Base case 153 | if (root == NULL) 154 | return ; 155 | 156 | // for node to be present 157 | if (root -> info == op){ 158 | // predecessor calculation 159 | if (root -> left != NULL) 160 | { 161 | struct node* temp = root -> left; 162 | while (temp -> right) 163 | temp = temp -> right; 164 | pred = temp ; 165 | } 166 | 167 | // successor calculation 168 | if (root -> right != NULL) 169 | { 170 | struct node* temp = root -> right ; 171 | while (temp -> left) 172 | temp = temp -> left ; 173 | succ = temp ; 174 | } 175 | // for the case above all 176 | return ; 177 | } 178 | 179 | // moving to left subtree for successor calculations 180 | if (root->info > op){ 181 | succ = root ; 182 | FindPS(root->left, op) ; 183 | } 184 | // moving to right subtree for predecessor calcualtions 185 | else{ 186 | pred = root ; 187 | FindPS(root->right, op) ; 188 | } 189 | } 190 | 191 | // main function begins here 192 | int main(){ 193 | printf("------------------\n"); 194 | printf("Binary Search Tree\n"); 195 | printf("------------------\n\n\n"); 196 | 197 | // variable declarations here 198 | int op = 0, flag = 0; // for storing value and option 199 | struct node *root = NULL; 200 | 201 | while(1){ 202 | printf("Select the option to be executed - \n"); 203 | printf("1. Insert\n2. Delete\n3. Display(all orders)\n4. Minimum Value\n5. Maximum Value\n6. Search\n7.Inorder Successor\n8.Preorder Predecessor\n9.Exit\n"); 204 | printf("\noption: "); 205 | scanf("%d", &op); 206 | 207 | // codition checking and menudriven execution 208 | switch(op){ 209 | 210 | // for insertion 211 | case 1: 212 | printf("\nPerforming Insertion...\n"); 213 | printf("Enter the number to be inserted: "); 214 | scanf("%d", &op); 215 | root = Insert(root, op); 216 | printf("\nAfter insertion(inorder): "); 217 | Inorder(root); 218 | printf("\n\n"); 219 | break; 220 | 221 | // for deletion 222 | case 2: 223 | printf("\nPerforming deletion...\n"); 224 | printf("Enter the number to be deleted: "); 225 | scanf("%d", &op); 226 | root = Delete(root, op); 227 | printf("After deletion(inorder): "); 228 | Inorder(root); 229 | printf("\n\n"); 230 | break; 231 | 232 | // for displaying 233 | case 3: 234 | printf("\nDisplaying all methods...\n"); 235 | printf("\nInorder - "); 236 | Inorder(root); 237 | printf("\nPreorder - "); 238 | Preorder(root); 239 | printf("\nPostorder - "); 240 | Postorder(root); 241 | printf("\n\n"); 242 | break; 243 | 244 | // for minimum value 245 | case 4: 246 | printf("The minimum value in the tree is: "); 247 | op = Minimum(root); 248 | printf("%d\n\n", op); 249 | break; 250 | 251 | // for maximum value 252 | case 5: 253 | printf("The maximum value in the tree is: "); 254 | op = Maximum(root); 255 | printf("%d\n\n", op); 256 | break; 257 | 258 | // for searching node 259 | case 6: 260 | printf("Enter the value to be searched for: "); 261 | scanf("%d", &op); 262 | op = Search(root, op); 263 | if(op == 1) 264 | printf("The given node exists!\n\n"); 265 | else 266 | printf("The given node doesn't exists!!\n\n"); 267 | break; 268 | 269 | // for inorder successor 270 | case 7: 271 | printf("Enter the node whose inorder successor you want: "); 272 | scanf("%d", &op); 273 | 274 | FindPS(root, op); 275 | if (succ != NULL) 276 | printf("It's successor is: %d\n\n", succ -> info); 277 | else 278 | printf("Oh!, No successor exists!\n\n"); 279 | break; 280 | 281 | // for inorder predecessor 282 | case 8: 283 | printf("Enter the node whose inorder predecessor you want: "); 284 | scanf("%d", &op); 285 | 286 | FindPS(root, op); 287 | if (pred != NULL) 288 | printf("It's predecessor is: %d\n\n", pred -> info); 289 | else 290 | printf("Oh!, No predecessor exists!\n\n"); 291 | break; 292 | 293 | // for exiting 294 | case 9: 295 | printf("\nExiting from module...\n"); 296 | return 0; // for successfull completion 297 | 298 | default: 299 | printf("\nOops!, Wrong option selected, Try again please...\n\n"); 300 | break; 301 | } 302 | } 303 | return 1; // for unsuccessful execution of code 304 | } 305 | 306 | 307 | -------------------------------------------------------------------------------- /c/Floyd's-Hare-And-Turtle.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | struct node 5 | { 6 | int data; 7 | struct node* next; 8 | }; 9 | 10 | struct node *head = NULL, *sentinel = NULL; 11 | int flag = 0; 12 | 13 | struct node* insert_node_last(struct node** head,struct node** sentinel,int data) 14 | { 15 | int n,i = 0; /* n => node to which the new node's next will point to */ 16 | struct node *temp,*new_node = (struct node*)malloc(sizeof (struct node)); 17 | new_node->data = data; 18 | if ( *sentinel != NULL ) 19 | { 20 | (*sentinel)->next = new_node; 21 | 22 | } 23 | else 24 | { 25 | *head = new_node; 26 | } 27 | *sentinel = new_node; 28 | while ( 1 ) 29 | { 30 | temp = *head; 31 | printf("\nEnter the node to whom the next pointer of this node will point to (Enter -1 for NULL):\n"); 32 | scanf("%d",&n); 33 | 34 | if ( n == -1 ) 35 | { 36 | new_node->next = NULL; 37 | break; 38 | } 39 | else 40 | { 41 | while ( i < n - 1 && temp != NULL ) 42 | { 43 | temp = temp->next; i++; 44 | } 45 | if ( i == n - 1 ) 46 | { 47 | if ( temp != NULL ) 48 | { 49 | new_node->next = temp; 50 | flag = 1; 51 | break; 52 | } 53 | else 54 | printf("Such a node does not exist\n"); 55 | } 56 | else 57 | printf("Such a node does not exist\n"); 58 | } 59 | } 60 | temp = *head; i = 1; 61 | while ( temp != NULL && flag != 1 ) 62 | { 63 | printf("(%d,%d)-->",i,temp->data); 64 | temp = temp->next; i++; 65 | } 66 | return NULL; 67 | } 68 | 69 | struct node* inc_steps(struct node* pt,int steps) 70 | { 71 | int i; struct node* temp = pt; 72 | for ( i = 0; i < steps ; i ++ ) 73 | { 74 | temp = temp->next; 75 | } 76 | return temp; 77 | } 78 | 79 | int main() 80 | { 81 | printf("\nEnter the nodes in the linked list\n"); 82 | int data, nos, period, lambda = 1, mu = 1; char op = 'Y'; 83 | while( ( op == 'Y' || op == 'y' ) && flag != 1 ) 84 | { 85 | printf("\nEnter the data for the new node\n"); 86 | scanf("%d",&data); 87 | insert_node_last(&head,&sentinel,data); 88 | if ( flag != 1 ) 89 | { printf("\nDo you want to insert more data ( Y or N )\n"); 90 | scanf("%c",&op); 91 | scanf("%c",&op); 92 | } 93 | } 94 | 95 | struct node *hare, *tortoise; 96 | hare = ( tortoise = head ) ; 97 | tortoise = tortoise ->next; 98 | hare = hare->next->next; 99 | nos = 1; 100 | 101 | while ( hare != tortoise && hare != NULL ) 102 | { 103 | tortoise = tortoise->next; 104 | hare = hare->next->next; 105 | nos++; 106 | } 107 | 108 | if ( hare == NULL ) 109 | { 110 | printf("\n :: No loop exists in the list :: \n"); 111 | return 0; 112 | } 113 | 114 | if ( hare == tortoise ) 115 | { 116 | period = nos; 117 | } 118 | 119 | tortoise = head; 120 | while ( tortoise != inc_steps(tortoise,period) ) 121 | { 122 | tortoise = tortoise->next; 123 | mu++; 124 | } 125 | if ( tortoise == inc_steps(tortoise,period) ) 126 | printf("\n :: The start node of the loop is at node no. %d :: \n",mu); 127 | 128 | hare = tortoise->next; 129 | 130 | while ( hare != tortoise ) 131 | { 132 | hare = hare->next; 133 | lambda++; 134 | } 135 | if ( hare == tortoise ) 136 | { 137 | printf("\n :: The length of the loop is %d :: \n ",lambda); 138 | } 139 | return 0; 140 | } 141 | -------------------------------------------------------------------------------- /c/HeapSort.c: -------------------------------------------------------------------------------- 1 | // ex- 12 c program for hrap sort 2 | #include 3 | #include 4 | 5 | // A heap has current size and array of elements 6 | struct MaxHeap{ 7 | int* array; 8 | int size; 9 | }; 10 | 11 | // function for insertion in heap 12 | void InsertHeap(int *array, int num, int location){ 13 | array[location] = num; 14 | 15 | } 16 | 17 | // function for deletion in heap 18 | void DeleteHeap(int *array, int num, int size){ 19 | int i = 0; 20 | while(1){ 21 | if(num == array[i]){ 22 | // do the stuffs 23 | for(;isize && 46 | maxHeap->array[Left] > maxHeap->array[Big]) 47 | Big = Left; 48 | 49 | if (Right < maxHeap->size && 50 | maxHeap->array[Right] > maxHeap->array[Big]) 51 | Big = Right; 52 | 53 | if (Big != index) 54 | { 55 | swap(&maxHeap->array[Big], &maxHeap->array[index]); 56 | maxHeapify(maxHeap, Big); 57 | } 58 | } 59 | 60 | // function to create maxHeap 61 | struct MaxHeap* createAndBuildHeap(int *array, int size){ 62 | int i; 63 | struct MaxHeap* maxHeap = 64 | (struct MaxHeap*) malloc(sizeof(struct MaxHeap)); 65 | maxHeap->size = size; 66 | maxHeap->array = array; 67 | 68 | for (i = (maxHeap->size - 2) / 2; i >= 0; --i) 69 | maxHeapify(maxHeap, i); 70 | return maxHeap; 71 | } 72 | 73 | // For heapsort function 74 | void heapSort(int* array, int size) 75 | { 76 | // building a heap 77 | struct MaxHeap* maxHeap = createAndBuildHeap(array, size); 78 | while (maxHeap->size > 1) 79 | { 80 | swap(&maxHeap->array[0], &maxHeap->array[maxHeap->size - 1]); 81 | --maxHeap->size; // Reduce heap size 82 | 83 | // root heapify 84 | maxHeapify(maxHeap, 0); 85 | } 86 | } 87 | 88 | // function to print the array 89 | void Display(int* arr, int size) 90 | { 91 | int i; 92 | for (i = 0; i < size; ++i) 93 | printf("%d ", arr[i]); 94 | } 95 | 96 | // main function begins here 97 | int main() 98 | { 99 | int size = 1; 100 | int array[size]; 101 | int op = 0; // for options 102 | int location = 0; // for tracking the location 103 | while(1){ 104 | printf("Enter the options to be executed: \n"); 105 | printf("1. Insert\n2. Delete\n3. Display\n4. Quit\n"); 106 | scanf("%d",&op); 107 | switch(op){ // using the swicth case 108 | case 1: printf("Enter the number to be inserted: "); 109 | scanf("%d",&op); 110 | InsertHeap(array, op, location); 111 | heapSort(array, size); 112 | location+=1; 113 | size+=1; 114 | printf("\nInserted Successfully!\n"); 115 | break; 116 | case 2: printf("Enter the number to be deleted: "); 117 | scanf("%d",&op); 118 | DeleteHeap(array, op, size); 119 | heapSort(array, size); 120 | location-=1; 121 | size-=1; 122 | break; 123 | case 3: printf("The array is: \n"); 124 | Display(array, size); 125 | break; 126 | case 4: printf("\nExiting...\n"); 127 | exit(0); 128 | default: printf("\nWrong Option selected!\n"); 129 | } 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /c/LinkedList.c: -------------------------------------------------------------------------------- 1 | // C program to Perform insertion and Sortion in a Single Linked List 2 | 3 | #include 4 | #include 5 | #include 6 | typedef struct node 7 | { 8 | int info; 9 | struct node *next; 10 | }nodetype; 11 | nodetype* insert(nodetype*); 12 | void sort(nodetype*); 13 | void main() 14 | { 15 | nodetype* left=NULL; 16 | nodetype* right=NULL; 17 | int ch,c; 18 | printf("Enter 1 for insert \nEnter 2 for sort \nEnter 3 for exit"); 19 | do 20 | { 21 | printf("\nEnter choice: "); 22 | scanf("%d",&ch); 23 | switch(ch) 24 | { 25 | case 1: 26 | right=insert(right); 27 | if(left==NULL) 28 | { 29 | left=right; 30 | } 31 | break; 32 | case 2: 33 | { 34 | sort(left); 35 | printf("\n"); 36 | break; 37 | } 38 | case 3: 39 | exit(1); 40 | default: 41 | { 42 | printf("invalid choice\n"); 43 | } 44 | } 45 | printf("Do you want to continue press 1: "); 46 | scanf("%d",&c); 47 | }while(c==1); 48 | } 49 | nodetype* insert(nodetype *r) 50 | { 51 | int n; 52 | nodetype *p; 53 | p=(nodetype*)malloc(sizeof(nodetype)); 54 | printf("\nEnter the number: "); 55 | scanf("%d",&n); 56 | if(p!=NULL) 57 | { 58 | p->info=n; 59 | p->next=NULL; 60 | if(r==NULL) 61 | { 62 | r=p; 63 | } 64 | else 65 | { 66 | r->next=p; 67 | r=p; 68 | } 69 | return(r); 70 | } 71 | else 72 | { 73 | printf("not enough memory"); 74 | } 75 | } 76 | void sort(nodetype *l) 77 | { 78 | nodetype *t; 79 | nodetype *s; 80 | int x; 81 | t=l; 82 | while(t!=NULL) 83 | { 84 | s=t->next; 85 | while(s!=NULL) 86 | { 87 | if(t->info>s->info) 88 | { 89 | x=t->info; 90 | t->info=s->info; 91 | s->info=x; 92 | } 93 | s=s->next; 94 | } 95 | t=t->next; 96 | } 97 | t=l; 98 | while(t!=NULL) 99 | { 100 | printf(" %d ",t->info); 101 | t=t->next; 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /c/Stack.c: -------------------------------------------------------------------------------- 1 | // C program to perform Push, Pop, and Display the elements in Stack Uning Array 2 | 3 | #include 4 | 5 | int stack[10],choice,n,top,x,i; // Declaration of variables 6 | 7 | void push(); 8 | void pop(); 9 | void display(); 10 | 11 | int main() 12 | { 13 | top = -1; // Initially there is no element in stack 14 | printf("\n Enter the size of STACK : "); 15 | scanf("%d",&n); 16 | printf("\nSTACK IMPLEMENTATION USING ARRAYS\n"); 17 | do 18 | { 19 | printf("\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n"); 20 | printf("\nEnter the choice : "); 21 | scanf("%d",&choice); 22 | switch(choice) 23 | { 24 | case 1: 25 | { 26 | push(); 27 | break; 28 | } 29 | case 2: 30 | { 31 | pop(); 32 | break; 33 | } 34 | case 3: 35 | { 36 | display(); 37 | break; 38 | } 39 | case 4: 40 | { 41 | break; 42 | } 43 | default: 44 | { 45 | printf ("\nInvalid Choice\n"); 46 | } 47 | } 48 | } 49 | while(choice!=4); 50 | return 0; 51 | } 52 | 53 | void push() 54 | { 55 | if(top >= n - 1) 56 | { 57 | printf("\nSTACK OVERFLOW\n"); 58 | 59 | } 60 | else 61 | { 62 | printf("Enter a value to be pushed : "); 63 | scanf("%d",&x); 64 | top++; // TOP is incremented after an element is pushed 65 | stack[top] = x; // The pushed element is made as TOP 66 | } 67 | } 68 | 69 | void pop() 70 | { 71 | if(top <= -1) 72 | { 73 | printf("\nSTACK UNDERFLOW\n"); 74 | } 75 | else 76 | { 77 | printf("\nThe popped element is %d",stack[top]); 78 | top--; // Decrement TOP after a pop 79 | } 80 | } 81 | 82 | void display() 83 | { 84 | if(top >= 0) 85 | { 86 | // Print the stack 87 | printf("\nELEMENTS IN THE STACK\n\n"); 88 | for(i = top ; i >= 0 ; i--) 89 | printf("%d\t",stack[i]); 90 | } 91 | else 92 | { 93 | printf("\nEMPTY STACK\n"); 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /c/bubbleSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void swapElements(int *a, int *b) //Swap values 4 | { 5 | int temp = *a; 6 | *a = *b; 7 | *b = temp; 8 | } 9 | 10 | 11 | void bubbleSort(int array[], int n){ //Bubble sort function 12 | 13 | int i, j; 14 | for (i = 0; i < n-1; i++) { 15 | 16 | for (j = 0; j < n-i-1; j++) { 17 | 18 | if (array[j] > array[j+1]) { 19 | swapElements(&array[j], &array[j+1]); 20 | } 21 | } 22 | } 23 | 24 | } 25 | 26 | void printArray(int array[], int size) //Print elements in the array 27 | { 28 | int i; 29 | for (i=0; i < size; i++){ 30 | printf("%d ", array[i]); 31 | } 32 | } 33 | 34 | int main() 35 | { 36 | int array[] = {1,8,4,7,33,100,-7,4,-100}; //Example Array 37 | int size = sizeof(array)/sizeof(array[0]); //No of elements in the array 38 | 39 | printf("\nArray Elements before sorting : "); 40 | printArray(array,size); 41 | 42 | bubbleSort(array, size); 43 | printf("\n\nArray elements after sorting using the bubble sort : "); 44 | printArray(array, size); 45 | 46 | return 0; 47 | } 48 | -------------------------------------------------------------------------------- /c/selectionSort.c: -------------------------------------------------------------------------------- 1 | C program for implementation of selection sort 2 | 3 | #include 4 | 5 | void swap(int *xp, int *yp) 6 | { 7 | int temp = *xp; 8 | *xp = *yp; 9 | *yp = temp; 10 | } 11 | 12 | void selectionSort(int arr[], int n) 13 | { 14 | int i, j, min_idx; 15 | 16 | // One by one move boundary of unsorted subarray 17 | for (i = 0; i < n-1; i++) 18 | { 19 | // Find the minimum element in unsorted array 20 | min_idx = i; 21 | for (j = i+1; j < n; j++) 22 | if (arr[j] < arr[min_idx]) 23 | min_idx = j; 24 | 25 | // Swap the found minimum element with the first element 26 | swap(&arr[min_idx], &arr[i]); 27 | } 28 | } 29 | 30 | /* Function to print an array */ 31 | void printArray(int arr[], int size) 32 | { 33 | int i; 34 | for (i=0; i < size; i++) 35 | cout << arr[i] << " "; 36 | cout << endl; 37 | } 38 | 39 | // Driver program to test above functions 40 | int main() 41 | { 42 | int arr[] = {64, 25, 12, 22, 11}; 43 | int n = sizeof(arr)/sizeof(arr[0]); 44 | selectionSort(arr, n); 45 | cout << "Sorted array: \n"; 46 | printArray(arr, n); 47 | return 0; 48 | } 49 | -------------------------------------------------------------------------------- /c/tower-of-hanoi.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void towers(int num, char fromtower, char totower, char auxtower); 4 | 5 | int main() 6 | { 7 | int num; 8 | 9 | printf("\nEnter the number of disks : "); 10 | scanf("%d", &num); 11 | printf("\nThe sequence of moves involved in the Tower of Hanoi are :\n"); 12 | towers(num, 'A', 'C', 'B'); 13 | printf("\n\n*** The disks are successfully shifted from tower A to tower C ***\n\n"); 14 | return 0; 15 | } 16 | void towers(int num, char fromtower, char totower, char auxtower) 17 | { 18 | if (num == 1) 19 | { 20 | printf("\n Move disk 1 from tower %c to tower %c", fromtower, totower); 21 | return; 22 | } 23 | towers(num - 1, fromtower, auxtower, totower); 24 | printf("\n Move disk %d from tower %c to tower %c", num, fromtower, totower); 25 | towers(num - 1, auxtower, totower, fromtower); 26 | } 27 | -------------------------------------------------------------------------------- /cpp/BFS.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | using namespace std; 4 | 5 | // This class represents a directed graph using 6 | // adjacency list representation 7 | class Graph 8 | { 9 | int V; // No. of vertices 10 | 11 | // Pointer to an array containing adjacency 12 | // lists 13 | vector> adj; 14 | public: 15 | Graph(int V); // Constructor 16 | 17 | // function to add an edge to graph 18 | void addEdge(int v, int w); 19 | 20 | // prints BFS traversal from a given source s 21 | void BFS(int s); 22 | }; 23 | 24 | Graph::Graph(int V) 25 | { 26 | this->V = V; 27 | adj.resize(V); 28 | } 29 | 30 | void Graph::addEdge(int v, int w) 31 | { 32 | adj[v].push_back(w); // Add w to v’s list. 33 | } 34 | 35 | void Graph::BFS(int s) 36 | { 37 | // Mark all the vertices as not visited 38 | vector visited; 39 | visited.resize(V,false); 40 | 41 | // Create a queue for BFS 42 | list queue; 43 | 44 | // Mark the current node as visited and enqueue it 45 | visited[s] = true; 46 | queue.push_back(s); 47 | 48 | while(!queue.empty()) 49 | { 50 | // Dequeue a vertex from queue and print it 51 | s = queue.front(); 52 | cout << s << " "; 53 | queue.pop_front(); 54 | 55 | // Get all adjacent vertices of the dequeued 56 | // vertex s. If a adjacent has not been visited, 57 | // then mark it visited and enqueue it 58 | for (auto adjecent: adj[s]) 59 | { 60 | if (!visited[adjecent]) 61 | { 62 | visited[adjecent] = true; 63 | queue.push_back(adjecent); 64 | } 65 | } 66 | } 67 | } 68 | 69 | // Driver program to test methods of graph class 70 | int main() 71 | { 72 | // Enter graph nodes: 73 | int n,x,y; 74 | cout<<"Enter no of nodes"<>n; 76 | Graph g(n); 77 | cout<<"Enter edges"<> x >>y; 80 | g.addEdge(x, y); 81 | } 82 | 83 | 84 | cout << "Following is Breadth First Traversal " 85 | << "(starting from vertex 2) \n"; 86 | g.BFS(2); 87 | 88 | return 0; 89 | } -------------------------------------------------------------------------------- /cpp/BubbleSort.cpp: -------------------------------------------------------------------------------- 1 | // Bubble sort 2 | 3 | #include 4 | using namespace std; 5 | 6 | void swap(int *xp, int *yp) 7 | { 8 | int temp = *xp; 9 | *xp = *yp; 10 | *yp = temp; 11 | } 12 | 13 | // A function to implement bubble sort 14 | void bubbleSort(int arr[], int n) 15 | { 16 | int i, j; 17 | for (i = 0; i < n-1; i++) 18 | 19 | // Last i elements are already in place 20 | for (j = 0; j < n-i-1; j++) 21 | if (arr[j] > arr[j+1]) 22 | swap(&arr[j], &arr[j+1]); 23 | } 24 | 25 | // Function to print an array 26 | void printArray(int arr[], int size) 27 | { 28 | int i; 29 | for (i = 0; i < size; i++) 30 | cout << arr[i] << " "; 31 | cout << endl; 32 | } 33 | 34 | // Entry Point 35 | int main() 36 | { 37 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 38 | int n = sizeof(arr)/sizeof(arr[0]); 39 | bubbleSort(arr, n); 40 | cout<<"Sorted array: \n"; 41 | printArray(arr, n); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /cpp/ExponentialSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binarySearch(int array[], int start, int end, int key) { 5 | if(start <= end) { 6 | int mid = (start + (end - start) /2); //mid location of the list 7 | if(array[mid] == key) 8 | return mid; 9 | if(array[mid] > key) 10 | return binarySearch(array, start, mid-1, key); 11 | else 12 | return binarySearch(array, mid+1, end, key); 13 | } 14 | return -1; 15 | } 16 | 17 | int exponentialSearch(int array[], int start, int end, int key){ 18 | if((end - start) <= 0) 19 | return -1; 20 | int i = 1; // as 2^0 = 1 21 | while(i < (end - start)){ 22 | if(array[i] < key) 23 | i *= 2; //i will increase as power of 2 24 | else 25 | break; //when array[i] corsses the key element 26 | } 27 | return binarySearch(array, i/2, i, key); //search item in form of binary search 28 | } 29 | 30 | int main() { 31 | int n, searchKey, loc; 32 | cout << "Enter number of items: "; 33 | cin >> n; 34 | int arr[n]; //create an array of size n 35 | cout << "Enter items: " << endl; 36 | for(int i = 0; i< n; i++) { 37 | cin >> arr[i]; 38 | } 39 | cout << "Enter search key to search in the list: "; 40 | cin >> searchKey; 41 | if((loc = exponentialSearch(arr, 0, n, searchKey)) >= 0) 42 | cout << "Item found at location: " << loc << endl; 43 | else 44 | cout << "Item is not found in the list." << endl; 45 | } 46 | -------------------------------------------------------------------------------- /cpp/FloydWarshall.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | const int inf = 1<<29; 6 | const int maxn = 100; 7 | 8 | int main(){ 9 | 10 | int edge[maxn][maxn] = {}; 11 | int distance[maxn][maxn] = {}; 12 | 13 | edge[0][1] = 10; 14 | edge[1][2] = 25; 15 | edge[2][3] = 1; 16 | edge[0][2] = 200; 17 | 18 | for(int i = 0;i < maxn;i++){ 19 | for(int j = 0;j < maxn;j++){ 20 | if (i == j) distance[i][j] = 0; 21 | else if (edge[i][j]) distance[i][j] = edge[i][j]; 22 | else distance[i][j] = inf; 23 | } 24 | } 25 | 26 | for(int k = 0;k < maxn;k++){ 27 | for(int i = 0;i < maxn;i++){ 28 | for(int j = 0;j < maxn;j++){ 29 | distance[i][j] = min(distance[i][j], distance[i][k]+distance[k][j]); 30 | } 31 | } 32 | } 33 | 34 | cout << "The minimum distance from 0 to 2 is " << distance[0][2] << endl; 35 | 36 | return 0; 37 | } 38 | -------------------------------------------------------------------------------- /cpp/Hashmap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | 10 | map gquiz1; 11 | gquiz1.insert(pair(1, 40)); 12 | gquiz1.insert(pair(2, 30)); 13 | gquiz1.insert(pair(3, 60)); 14 | gquiz1.insert(pair(4, 20)); 15 | gquiz1.insert(pair(5, 50)); 16 | gquiz1.insert(pair(6, 50)); 17 | gquiz1.insert(pair(7, 10)); 18 | 19 | map::iterator itr; 20 | cout << "\nThe map gquiz1 is : \n"; 21 | cout << "\tKEY\tELEMENT\n"; 22 | for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { 23 | cout << '\t' << itr->first 24 | << '\t' << itr->second << '\n'; 25 | } 26 | cout << endl; 27 | 28 | map gquiz2(gquiz1.begin(), gquiz1.end()); 29 | 30 | cout << "\nThe map gquiz2 after" 31 | << " assign from gquiz1 is : \n"; 32 | cout << "\tKEY\tELEMENT\n"; 33 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 34 | cout << '\t' << itr->first 35 | << '\t' << itr->second << '\n'; 36 | } 37 | cout << endl; 38 | 39 | cout << "\ngquiz2 after removal of" 40 | " elements less than key=3 : \n"; 41 | cout << "\tKEY\tELEMENT\n"; 42 | gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); 43 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 44 | cout << '\t' << itr->first 45 | << '\t' << itr->second << '\n'; 46 | } 47 | 48 | int num; 49 | num = gquiz2.erase(4); 50 | cout << "\ngquiz2.erase(4) : "; 51 | cout << num << " removed \n"; 52 | cout << "\tKEY\tELEMENT\n"; 53 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 54 | cout << '\t' << itr->first 55 | << '\t' << itr->second << '\n'; 56 | } 57 | cout << endl; 58 | 59 | cout << "gquiz1.lower_bound(5) : " 60 | << "\tKEY = "; 61 | cout << gquiz1.lower_bound(5)->first << '\t'; 62 | cout << "\tELEMENT = " 63 | << gquiz1.lower_bound(5)->second << endl; 64 | cout << "gquiz1.upper_bound(5) : " 65 | << "\tKEY = "; 66 | cout << gquiz1.upper_bound(5)->first << '\t'; 67 | cout << "\tELEMENT = " 68 | << gquiz1.upper_bound(5)->second << endl; 69 | 70 | return 0; 71 | } 72 | -------------------------------------------------------------------------------- /cpp/JumpSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | int jump_Search(int a[], int n, int item) { 6 | int i = 0; 7 | int m = sqrt(n); 8 | 9 | while(a[m] <= item && m < n) { 10 | // the control will continue to jump the blocks 11 | i = m; // shift the block 12 | m += sqrt(n); 13 | if(m > n - 1) // if m exceeds the array size 14 | return -1; 15 | } 16 | 17 | for(int x = i; x> n; 28 | int arr[n]; //creating an array of size n 29 | cout << "\n Enter items: "; 30 | 31 | for(int i = 0; i< n; i++) { 32 | cin >> arr[i]; 33 | } 34 | 35 | cout << "\n Enter search key to be found in the array: "; 36 | cin >> item; 37 | loc = jump_Search(arr, n, item); 38 | if(loc>=0) 39 | cout << "\n Item found at location: " << loc; 40 | else 41 | cout << "\n Item is not found in the list."; 42 | } 43 | -------------------------------------------------------------------------------- /cpp/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 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 | int n1 = m - l + 1; 11 | int n2 = r - m; 12 | 13 | // Create temp arrays 14 | int L[n1], R[n2]; 15 | 16 | // Copy data to temp arrays L[] and R[] 17 | for(int i = 0; i < n1; i++) 18 | L[i] = arr[l + i]; 19 | for(int j = 0; j < n2; j++) 20 | R[j] = arr[m + 1 + j]; 21 | 22 | // Merge the temp arrays back into arr[l..r] 23 | 24 | // Initial index of first subarray 25 | int i = 0; 26 | 27 | // Initial index of second subarray 28 | int j = 0; 29 | 30 | // Initial index of merged subarray 31 | int k = l; 32 | 33 | while (i < n1 && j < n2) 34 | { 35 | if (L[i] <= R[j]) 36 | { 37 | arr[k] = L[i]; 38 | i++; 39 | } 40 | else 41 | { 42 | arr[k] = R[j]; 43 | j++; 44 | } 45 | k++; 46 | } 47 | 48 | // Copy the remaining elements of 49 | // L[], if there are any 50 | while (i < n1) 51 | { 52 | arr[k] = L[i]; 53 | i++; 54 | k++; 55 | } 56 | 57 | // Copy the remaining elements of 58 | // R[], if there are any 59 | while (j < n2) 60 | { 61 | arr[k] = R[j]; 62 | j++; 63 | k++; 64 | } 65 | } 66 | 67 | // l is for left index and r is 68 | // right index of the sub-array 69 | // of arr to be sorted */ 70 | void mergeSort(int arr[], int l, int r) 71 | { 72 | if (l < r) 73 | { 74 | 75 | // Same as (l+r)/2, but avoids 76 | // overflow for large l and h 77 | int m = l + (r - l) / 2; 78 | 79 | // Sort first and second halves 80 | mergeSort(arr, l, m); 81 | mergeSort(arr, m + 1, r); 82 | 83 | merge(arr, l, m, r); 84 | } 85 | } 86 | 87 | // UTILITY FUNCTIONS 88 | // Function to print an array 89 | void printArray(int A[], int size) 90 | { 91 | for(int i = 0; i < size; i++) 92 | cout << A[i] << " "; 93 | } 94 | 95 | // Driver code 96 | int main() 97 | { 98 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 99 | int arr_size = sizeof(arr) / sizeof(arr[0]); 100 | 101 | cout << "Given array is \n"; 102 | printArray(arr, arr_size); 103 | 104 | mergeSort(arr, 0, arr_size - 1); 105 | 106 | cout << "\nSorted array is \n"; 107 | printArray(arr, arr_size); 108 | return 0; 109 | } 110 | -------------------------------------------------------------------------------- /cpp/Number_of_island: -------------------------------------------------------------------------------- 1 | /* Problem-link: https://leetcode.com/problems/number-of-islands/ */ 2 | class Solution { 3 | public: 4 | void fn(vector>& grid,int n,int m,int a,int b){ 5 | if(a<0 || b<0 ||a>=n || b>=m ||grid[a][b]=='0') 6 | return; 7 | grid[a][b]='0'; 8 | fn(grid,n,m,a+1,b); 9 | fn(grid,n,m,a-1,b); 10 | fn(grid,n,m,a,b-1); 11 | fn(grid,n,m,a,b+1); 12 | 13 | } 14 | int numIslands(vector>& grid) { 15 | int n=grid.size(); 16 | if(n==0) 17 | return 0;int a=0; 18 | int m=grid[0].size(); 19 | for(int i=0;i& v,TreeNode* root){ 17 | if(root==NULL) 18 | return ; 19 | in(v,root->left); 20 | v.push_back(root->val); 21 | in(v,root->right); 22 | 23 | } 24 | int kthSmallest(TreeNode* root, int k) { 25 | 26 | vector v; 27 | in(v,root); 28 | 29 | return v[k-1]; 30 | 31 | 32 | } 33 | }; 34 | -------------------------------------------------------------------------------- /cpp/TreeTraversals.cpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | TREE TRAVERSALS (CPP) 3 | 4 | Test case: 5 | Input: 6 | 5 7 | 1 2 3 4 5 8 | 9 | Ouput: (PreOrder, InOrder, PostOrder) 10 | 1 2 3 4 5 11 | 1 2 3 4 5 12 | 5 4 3 2 1 13 | *******************************************************************************/ 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | // Create tree data structure 22 | class tree 23 | { 24 | public: 25 | int data; 26 | tree *left, *right; 27 | }; 28 | 29 | // Create single Node 30 | tree *createNode(int x) 31 | { 32 | tree *n = new tree(); 33 | n->data = x; 34 | (*n).left = NULL; 35 | n->right = NULL; 36 | return n; 37 | } 38 | 39 | // Create/Insert into BinarySearchTree 40 | tree *binarySearchTree(tree *root, int x) 41 | { 42 | if (root == NULL) 43 | return createNode(x); 44 | if (x < root->data) 45 | root->left = binarySearchTree(root->left, x); 46 | else 47 | root->right = binarySearchTree(root->right, x); 48 | 49 | return root; 50 | } 51 | 52 | // Prints Pre-Order Traversal 53 | // 1. Print data, 2. Goto left node 3. Goto right node 54 | void preorderTraversal(tree *root) 55 | { 56 | if (root == NULL) 57 | return; 58 | cout << root->data << " "; 59 | preorderTraversal(root->left); 60 | preorderTraversal(root->right); 61 | } 62 | 63 | // Prints in-Order Traversal 64 | // 1. Goto left node, 2. Print data, 3. Goto right node 65 | void inorderTraversal(tree *root) 66 | { 67 | if (root == NULL) 68 | return; 69 | inorderTraversal(root->left); 70 | cout << root->data << " "; 71 | inorderTraversal(root->right); 72 | } 73 | 74 | // Prints Post-Order Traversal 75 | // 1. Goto left node, 2. Goto right node, 3. Print data 76 | void postorderTraversal(tree *root) 77 | { 78 | if (root == NULL) 79 | return; 80 | postorderTraversal(root->left); 81 | postorderTraversal(root->right); 82 | cout << root->data << " "; 83 | } 84 | 85 | int main() 86 | { 87 | // Read the size of the array 88 | int n; 89 | cin >> n; 90 | 91 | // Read the array elements and create a BST out of it 92 | tree *root = NULL; 93 | while (n--) 94 | { 95 | int x; 96 | cin >> x; 97 | root = binarySearchTree(root, x); 98 | } 99 | 100 | // Print PreOrder Traversal 101 | preorderTraversal(root); 102 | cout << "\n"; 103 | 104 | // Print In-Order Traversal 105 | inorderTraversal(root); 106 | cout << "\n"; 107 | 108 | // Print Post-Order Traversal 109 | postorderTraversal(root); 110 | cout << "\n"; 111 | 112 | return 0; 113 | } -------------------------------------------------------------------------------- /cpp/addMatrix.cpp: -------------------------------------------------------------------------------- 1 | (Add Two Matrix Using Multi-dimensional Arrays) 2 | #include 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int r, c, a[100][100], b[100][100], sum[100][100], i, j; 8 | 9 | cout << "Enter number of rows (between 1 and 100): "; 10 | cin >> r; 11 | 12 | cout << "Enter number of columns (between 1 and 100): "; 13 | cin >> c; 14 | 15 | cout << endl << "Enter elements of 1st matrix: " << endl; 16 | 17 | // Storing elements of first matrix entered by user. 18 | for(i = 0; i < r; ++i) 19 | for(j = 0; j < c; ++j) 20 | { 21 | cout << "Enter element a" << i + 1 << j + 1 << " : "; 22 | cin >> a[i][j]; 23 | } 24 | 25 | // Storing elements of second matrix entered by user. 26 | cout << endl << "Enter elements of 2nd matrix: " << endl; 27 | for(i = 0; i < r; ++i) 28 | for(j = 0; j < c; ++j) 29 | { 30 | cout << "Enter element b" << i + 1 << j + 1 << " : "; 31 | cin >> b[i][j]; 32 | } 33 | 34 | // Adding Two matrices 35 | for(i = 0; i < r; ++i) 36 | for(j = 0; j < c; ++j) 37 | sum[i][j] = a[i][j] + b[i][j]; 38 | 39 | // Displaying the resultant sum matrix. 40 | cout << endl << "Sum of two matrix is: " << endl; 41 | for(i = 0; i < r; ++i) 42 | for(j = 0; j < c; ++j) 43 | { 44 | cout << sum[i][j] << " "; 45 | if(j == c - 1) 46 | cout << endl; 47 | } 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /cpp/armstrongNumber.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | int main() 5 | { 6 | long long int n,num,sum=0,i=0; 7 | cin>>n; 8 | num=n; 9 | for(;n;i++) 10 | n/=10; 11 | n=num; 12 | while(n) 13 | { 14 | long long int x=n%10; 15 | n/=10; 16 | x=pow(x, i); 17 | sum+=x; 18 | } 19 | if(sum==num) 20 | cout<<"It's is a Armstrong Number\n"; 21 | else 22 | cout<<"It's is a not Armstrong Number\n"; 23 | } 24 | -------------------------------------------------------------------------------- /cpp/insertion_in_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | // A complete working C program to demonstrate all insertion methods 2 | // on Linked List 3 | #include 4 | #include 5 | 6 | // A linked list node 7 | struct Node 8 | { 9 | int data; 10 | struct Node *next; 11 | }; 12 | 13 | /* Given a reference (pointer to pointer) to the head of a list and 14 | an int, inserts a new node on the front of the list. */ 15 | void push(struct Node** head_ref, int new_data) 16 | { 17 | /* 1. allocate node */ 18 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 19 | 20 | /* 2. put in the data */ 21 | new_node->data = new_data; 22 | 23 | /* 3. Make next of new node as head */ 24 | new_node->next = (*head_ref); 25 | 26 | /* 4. move the head to point to the new node */ 27 | (*head_ref) = new_node; 28 | } 29 | 30 | /* Given a node prev_node, insert a new node after the given 31 | prev_node */ 32 | void insertAfter(struct Node* prev_node, int new_data) 33 | { 34 | /*1. check if the given prev_node is NULL */ 35 | if (prev_node == NULL) 36 | { 37 | printf("the given previous node cannot be NULL"); 38 | return; 39 | } 40 | 41 | /* 2. allocate new node */ 42 | struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); 43 | 44 | /* 3. put in the data */ 45 | new_node->data = new_data; 46 | 47 | /* 4. Make next of new node as next of prev_node */ 48 | new_node->next = prev_node->next; 49 | 50 | /* 5. move the next of prev_node as new_node */ 51 | prev_node->next = new_node; 52 | } 53 | 54 | /* Given a reference (pointer to pointer) to the head 55 | of a list and an int, appends a new node at the end */ 56 | void append(struct Node** head_ref, int new_data) 57 | { 58 | /* 1. allocate node */ 59 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 60 | 61 | struct Node *last = *head_ref; /* used in step 5*/ 62 | 63 | /* 2. put in the data */ 64 | new_node->data = new_data; 65 | 66 | /* 3. This new node is going to be the last node, so make next of 67 | it as NULL*/ 68 | new_node->next = NULL; 69 | 70 | /* 4. If the Linked List is empty, then make the new node as head */ 71 | if (*head_ref == NULL) 72 | { 73 | *head_ref = new_node; 74 | return; 75 | } 76 | 77 | /* 5. Else traverse till the last node */ 78 | while (last->next != NULL) 79 | last = last->next; 80 | 81 | /* 6. Change the next of last node */ 82 | last->next = new_node; 83 | return; 84 | } 85 | 86 | // This function prints contents of linked list starting from head 87 | void printList(struct Node *node) 88 | { 89 | while (node != NULL) 90 | { 91 | printf(" %d ", node->data); 92 | node = node->next; 93 | } 94 | } 95 | 96 | /* Driver program to test above functions*/ 97 | int main() 98 | { 99 | /* Start with the empty list */ 100 | struct Node* head = NULL; 101 | 102 | // Insert 6. So linked list becomes 6->NULL 103 | append(&head, 6); 104 | 105 | // Insert 7 at the beginning. So linked list becomes 7->6->NULL 106 | push(&head, 7); 107 | 108 | // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL 109 | push(&head, 1); 110 | 111 | // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL 112 | append(&head, 4); 113 | 114 | // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL 115 | insertAfter(head->next, 8); 116 | 117 | printf("\n Created Linked list is: "); 118 | printList(head); 119 | 120 | return 0; 121 | } 122 | -------------------------------------------------------------------------------- /cpp/palindromeSeries.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() { 4 | int n1=0,n2=1,n3,i,num; 5 | cout << "Enter number of elements: "; 6 | cin >> num; 7 | cout << n1 << " " << n2 << " "; 8 | for(i=2; i 2 | using namespace std; 3 | int main () { 4 | int arr[] = {50, 1, 100, 1000, 12}; 5 | int n = sizeof(arr)/sizeof(arr[0]); 6 | for(int i =0; i 4 | using namespace std; 5 | 6 | void swap(int *xp, int *yp) 7 | { 8 | int temp = *xp; 9 | *xp = *yp; 10 | *yp = temp; 11 | } 12 | 13 | void selectionSort(int arr[], int n) 14 | { 15 | int i, j, min_idx; 16 | 17 | // One by one move boundary of unsorted subarray 18 | for (i = 0; i < n-1; i++) 19 | { 20 | // Find the minimum element in unsorted array 21 | min_idx = i; 22 | for (j = i+1; j < n; j++) 23 | if (arr[j] < arr[min_idx]) 24 | min_idx = j; 25 | 26 | // Swap the found minimum element with the first element 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 | // Driver program to test above functions 41 | int main() 42 | { 43 | int arr[] = {64, 25, 12, 22, 11}; 44 | int n = sizeof(arr)/sizeof(arr[0]); 45 | selectionSort(arr, n); 46 | cout << "Sorted array: \n"; 47 | printArray(arr, n); 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /csharp/BinarySearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class GFG { 4 | // Returns index of x if it is present in 5 | // arr[l..r], else return -1 6 | static int binarySearch(int[] arr, int l, 7 | int r, int x) 8 | { 9 | if (r >= l) { 10 | int mid = l + (r - l) / 2; 11 | 12 | // If the element is present at the 13 | // middle itself 14 | if (arr[mid] == x) 15 | return mid; 16 | 17 | // If element is smaller than mid, then 18 | // it can only be present in left subarray 19 | if (arr[mid] > x) 20 | return binarySearch(arr, l, mid - 1, x); 21 | 22 | // Else the element can only be present 23 | // in right subarray 24 | return binarySearch(arr, mid + 1, r, x); 25 | } 26 | 27 | // We reach here when element is not present 28 | // in array 29 | return -1; 30 | } 31 | 32 | // Driver method to test above 33 | public static void Main() 34 | { 35 | 36 | int[] arr = { 2, 3, 4, 10, 40 }; 37 | int n = arr.Length; 38 | int x = 10; 39 | 40 | int result = binarySearch(arr, 0, n - 1, x); 41 | 42 | if (result == -1) 43 | Console.WriteLine("Element not present"); 44 | else 45 | Console.WriteLine("Element found at index " 46 | + result); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /csharp/BubbleSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | class BubbleSort { 3 | static void Main(string[] args) { 4 | 5 | int[] arr = { 78, 55, 45, 98, 13, 8, 5, 4, 8, 1 }; 6 | int temp; 7 | 8 | Console.WriteLine("Original array: "); 9 | foreach (int p in arr) 10 | Console.WriteLine(p + " "); 11 | 12 | for (int j = 0; j <= arr.Length - 2; j++) { 13 | 14 | for (int i = 0; i <= arr.Length - 2; i++) { 15 | 16 | if (arr[i] > arr[i + 1]) { 17 | temp= arr[i + 1]; 18 | arr[i + 1] = arr[i]; 19 | arr[i] = temp; 20 | } 21 | } 22 | } 23 | 24 | Console.WriteLine("Sorted Array:"); 25 | foreach (int p in arr) 26 | Console.WriteLine(p + " "); 27 | Console.Read(); 28 | } 29 | } -------------------------------------------------------------------------------- /csharp/Selectionsort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class SelectionSort{ 4 | static void Main(string[] args){ 5 | 6 | int[] array = new int[10] {34, 78, 12, 44, 23, 89, 67, 99 ,1 ,56}; 7 | int num = 10; 8 | 9 | Console.WriteLine("Selection Sort!"); 10 | Console.Write("Here is the initial array: "); 11 | 12 | for (int i = 0; i < num; i++){ 13 | Console.Write(array[i] + " "); 14 | } 15 | 16 | int temp, small; 17 | 18 | for (int i = 0; i < num -1; i++){ 19 | small = i; 20 | for (int j = i + 1; j < num; j++){ 21 | if (array[j] < array[small]){ 22 | small = j; 23 | } 24 | } 25 | 26 | temp = array[small]; 27 | array[small] = array[i]; 28 | array[i] = temp; 29 | } 30 | 31 | Console.WriteLine(); 32 | Console.Write("Selection sorted array is: "); 33 | for (int i = 0; i < num; i++){ 34 | Console.Write(array[i] + " "); 35 | } 36 | 37 | // for stopping 38 | Console.ReadLine(); 39 | } 40 | } -------------------------------------------------------------------------------- /golang/ArmstrongNumber.go: -------------------------------------------------------------------------------- 1 | //Program to check armstrong number 2 | 3 | package main 4 | 5 | import "fmt" 6 | 7 | func main() { 8 | var number, tempNumber, remainder int //declaring variables for execution 9 | var result int = 0 10 | 11 | fmt.Print("Enter a number to be checked: ") 12 | fmt.Scan(&number) 13 | 14 | tempNumber = number 15 | 16 | //executing the logic for checking an armstrong number 17 | for { 18 | remainder = tempNumber % 10 19 | result += remainder * remainder * remainder 20 | tempNumber /= 10 21 | 22 | if tempNumber == 0 { 23 | break 24 | } 25 | } 26 | 27 | if result == number { 28 | fmt.Printf("%d is an Armstrong number.", number) 29 | } else { 30 | fmt.Printf("%d is not an armstrong number.", number) 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /golang/BinarySearch.go: -------------------------------------------------------------------------------- 1 | //Binary Search in Golang 2 | 3 | package main 4 | import "fmt" 5 | func binarySearch(needle int, haystack[]int) bool { 6 | low := 0 7 | high := len(haystack) - 1 8 | 9 | for low<=high{ 10 | median:=(low+high) / 2 11 | 12 | if haystack[median] < needle { 13 | low = median + 1 14 | }else{ 15 | high = median - 1 16 | } 17 | } 18 | 19 | if low == len(haystack) || haystack[low] != needle { 20 | return false 21 | } 22 | 23 | return true 24 | } 25 | 26 | func main(){ 27 | 28 | length := 0 29 | fmt.Println("Enter the number of inputs: ") 30 | fmt.Scanln(&length) 31 | 32 | fmt.Println("Enter the inputs: ") 33 | 34 | items := make([]int, length) 35 | for i := 0; i < length; i++ { 36 | fmt.Scanln(&items[i]) 37 | } 38 | 39 | number := 0 40 | fmt.Println("Enter the number to be searched for: ") 41 | fmt.Scanln(&number) 42 | 43 | //function calling 44 | fmt.Println(binarySearch(number, items)) 45 | } 46 | -------------------------------------------------------------------------------- /golang/InsertionSort.go: -------------------------------------------------------------------------------- 1 | //Program for insertion sort 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | ) 8 | 9 | func main() { 10 | 11 | length := 0 12 | fmt.Println("Enter the number of inputs: ") 13 | fmt.Scanln(&length) 14 | 15 | fmt.Println("Enter the inputs: ") 16 | 17 | slice := make([]int, length) 18 | for i := 0; i < length; i++ { 19 | fmt.Scanln(&slice[i]) 20 | } 21 | 22 | fmt.Println("\nUnSorted array is: \n\n", slice) 23 | insertionsort(slice) 24 | fmt.Println("\nSorted array is: \n", slice, "\n") 25 | } 26 | 27 | func insertionsort(items []int) { 28 | var n = len(items) 29 | for i := 1; i < n; i++ { 30 | j := i 31 | for j > 0 { 32 | if items[j-1] > items[j] { 33 | items[j-1], items[j] = items[j], items[j-1] 34 | } 35 | j = j - 1 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /golang/MergeSort.go: -------------------------------------------------------------------------------- 1 | // Merge Sort in Golang 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | 10 | length := 0 11 | fmt.Println("Enter the number of inputs: ") 12 | fmt.Scanln(&length) 13 | 14 | fmt.Println("Enter the inputs: ") 15 | 16 | slice := make([]int, length) 17 | for i := 0; i < length; i++ { 18 | fmt.Scanln(&slice[i]) 19 | } 20 | 21 | fmt.Println("\nUnSorted array is: \n\n", slice) 22 | fmt.Println("\nUnSorted array is: \n\n", slice) 23 | mergeSort(slice) 24 | fmt.Println("\nSorted array is: \n", slice, "\n") 25 | } 26 | func mergeSort(items []int) []int { 27 | var num = len(items) 28 | 29 | if num == 1 { 30 | return items 31 | } 32 | 33 | middle := int(num / 2) 34 | var ( 35 | left = make([]int, middle) 36 | right = make([]int, num-middle) 37 | ) 38 | for i := 0; i < num; i++ { 39 | if i < middle { 40 | left[i] = items[i] 41 | } else { 42 | right[i-middle] = items[i] 43 | } 44 | } 45 | 46 | return merge(mergeSort(left), mergeSort(right)) 47 | } 48 | 49 | func merge(left, right []int) (result []int) { 50 | result = make([]int, len(left)+len(right)) 51 | 52 | i := 0 53 | for len(left) > 0 && len(right) > 0 { 54 | if left[0] < right[0] { 55 | result[i] = left[0] 56 | left = left[1:] 57 | } else { 58 | result[i] = right[0] 59 | right = right[1:] 60 | } 61 | i++ 62 | } 63 | 64 | for j := 0; j < len(left); j++ { 65 | result[i] = left[j] 66 | i++ 67 | } 68 | for j := 0; j < len(right); j++ { 69 | result[i] = right[j] 70 | i++ 71 | } 72 | 73 | return 74 | } 75 | -------------------------------------------------------------------------------- /golang/Palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func checkPalindrome(num int) string { 8 | input_num := num 9 | var remainder int 10 | res := 0 11 | for num > 0 { 12 | remainder = num % 10 13 | res = (res * 10) + remainder 14 | num = num / 10 15 | } 16 | if input_num == res { 17 | return "Palindrome" 18 | } else { 19 | return "Not a Palindrome" 20 | } 21 | } 22 | 23 | func main() { 24 | fmt.Println("Enter the number to check if it is a palindrome or not: ") 25 | var i int 26 | _, err := fmt.Scanf("%d", &i) 27 | if err != nil { 28 | fmt.Println("Error in input") 29 | } 30 | fmt.Println(checkPalindrome(i)) 31 | } 32 | -------------------------------------------------------------------------------- /golang/PascalsTr.go: -------------------------------------------------------------------------------- 1 | //Progra, to print the pascals triangle 2 | 3 | package main 4 | 5 | import "fmt" 6 | 7 | func main() { 8 | var rows int 9 | var temp int = 1 10 | fmt.Print("Enter the number of pascals traingle rows: ") 11 | fmt.Scan(&rows) 12 | 13 | for i := 0; i < rows; i++ { 14 | for j := 1; j <= rows-i; j++ { 15 | fmt.Print(" ") 16 | } 17 | for k := 0; k <= i; k++ { 18 | 19 | if k == 0 || i == 0 { 20 | temp = 1 21 | } else { 22 | temp = temp * (i - k + 1) / k 23 | } 24 | fmt.Printf(" %d", temp) 25 | } 26 | fmt.Println("") 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /golang/Readme.md: -------------------------------------------------------------------------------- 1 | # Algorithms and Data-Structures in Golang 2 | -------------------------------------------------------------------------------- /golang/SelectionSort.go: -------------------------------------------------------------------------------- 1 | // Program for selection-sort 2 | package main 3 | 4 | import ( 5 | "fmt" 6 | ) 7 | 8 | func main() { 9 | 10 | length := 0 11 | fmt.Println("Enter the number of inputs: ") 12 | fmt.Scanln(&length) 13 | 14 | fmt.Println("Enter the inputs: ") 15 | 16 | slice := make([]int, length) 17 | for i := 0; i < length; i++ { 18 | fmt.Scanln(&slice[i]) 19 | } 20 | 21 | fmt.Println("\nUnSorted array is: \n\n", slice) 22 | fmt.Println("\nUnSorted array is: \n\n", slice)sort(slice) 23 | fmt.Println("\nSorted array is: \n", slice, "\n") 24 | } 25 | 26 | func selectionsort(items []int) { 27 | var n = len(items) 28 | for i := 0; i < n; i++ { 29 | var minIdx = i 30 | for j := i; j < n; j++ { 31 | if items[j] < items[minIdx] { 32 | minIdx = j 33 | } 34 | } 35 | items[i], items[minIdx] = items[minIdx], items[i] 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /golang/quickSort.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("before sorting\n", slice) 13 | quicksort(slice) 14 | fmt.Println("after sorting\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 | } 53 | -------------------------------------------------------------------------------- /java/BinarySearch.java: -------------------------------------------------------------------------------- 1 | class BinarySearch { 2 | // Returns index of x if it is present in arr[l.. 3 | // r], else return -1 4 | int binarySearch(int arr[], int l, int r, int x) 5 | { 6 | if (r >= l) { 7 | int mid = l + (r - l) / 2; 8 | 9 | // If the element is present at the 10 | // middle itself 11 | if (arr[mid] == x) 12 | return mid; 13 | 14 | // If element is smaller than mid, then 15 | // it can only be present in left subarray 16 | if (arr[mid] > x) 17 | return binarySearch(arr, l, mid - 1, x); 18 | 19 | // Else the element can only be present 20 | // in right subarray 21 | return binarySearch(arr, mid + 1, r, x); 22 | } 23 | 24 | // We reach here when element is not present 25 | // in array 26 | return -1; 27 | } 28 | 29 | // Driver method to test above 30 | public static void main(String args[]) 31 | { 32 | BinarySearch ob = new BinarySearch(); 33 | int arr[] = { 2, 3, 4, 10, 40 }; 34 | int n = arr.length; 35 | int x = 10; 36 | int result = ob.binarySearch(arr, 0, n - 1, x); 37 | if (result == -1) 38 | System.out.println("Element not present"); 39 | else 40 | System.out.println("Element found at index " + result); 41 | } 42 | } -------------------------------------------------------------------------------- /java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class BubbleSort { 4 | void bubbleSort(int array[]) { 5 | int size = array.length; 6 | 7 | // run loops two times: one for walking throught the array 8 | // and the other for comparison 9 | for (int i = 0; i < size - 1; i++) 10 | for (int j = 0; j < size - i - 1; j++) 11 | 12 | // To sort in descending order, change > to < in this line. 13 | if (array[j] > array[j + 1]) { 14 | 15 | // swap if greater is at the rear position 16 | int temp = array[j]; 17 | array[j] = array[j + 1]; 18 | array[j + 1] = temp; 19 | } 20 | } 21 | 22 | // usage 23 | public static void main(String args[]) { 24 | int[] data = { -2, 45, 0, 11, -9 }; 25 | BubbleSort bs = new BubbleSort(); 26 | bs.bubbleSort(data); 27 | System.out.println("Sorted Array:"); 28 | System.out.println(Arrays.toString(data)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | class InsertionSort { 2 | /*Function to sort array using insertion sort*/ 3 | void sort(int arr[]) 4 | { 5 | int n = arr.length; 6 | for (int i = 1; i < n; ++i) { 7 | int key = arr[i]; 8 | int j = i - 1; 9 | 10 | /* Move elements of arr[0..i-1], that are 11 | greater than key, to one position ahead 12 | of their current position */ 13 | while (j >= 0 && arr[j] > key) { 14 | arr[j + 1] = arr[j]; 15 | j = j - 1; 16 | } 17 | arr[j + 1] = key; 18 | } 19 | } 20 | 21 | /* A utility function to print array of size n*/ 22 | static void printArray(int arr[]) 23 | { 24 | int n = arr.length; 25 | for (int i = 0; i < n; ++i) 26 | System.out.print(arr[i] + " "); 27 | 28 | System.out.println(); 29 | } 30 | 31 | // Driver method 32 | public static void main(String args[]) 33 | { 34 | int arr[] = { 12, 11, 13, 5, 6 }; 35 | 36 | InsertionSort ob = new InsertionSort(); 37 | ob.sort(arr); 38 | 39 | printArray(arr); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /java/LinearSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class LinearSearch 4 | { 5 | public static void main(String args[]) 6 | { 7 | int c, n, search, array[]; 8 | 9 | Scanner in = new Scanner(System.in); 10 | System.out.println("Enter number of elements "); 11 | n = in.nextInt(); 12 | array = new int[n]; 13 | 14 | System.out.println("Enter those " + n + " elements "+ "(Press Enter after each):"); 15 | 16 | for (c = 0; c < n; c++) 17 | 18 | array[c] = in.nextInt(); 19 | 20 | System.out.println("Enter value to find"); 21 | search = in.nextInt(); 22 | for (c = 0; c < n; c++) 23 | { 24 | if (array[c] == search) /* Searching element is present */ 25 | { 26 | System.out.println(search + " is present at location " + (c + 1) + "."); 27 | break; 28 | } 29 | } 30 | if (c == n) /* Element to search isn't present */ 31 | System.out.println(search + " isn't present in array."); 32 | } 33 | } -------------------------------------------------------------------------------- /java/MergeSort.java: -------------------------------------------------------------------------------- 1 | /* Java program for Merge Sort */ 2 | class MergeSort { 3 | // Merges two subarrays of arr[]. 4 | // First subarray is arr[l..m] 5 | // Second subarray is arr[m+1..r] 6 | void merge(int arr[], int l, int m, int r) 7 | { 8 | // Find sizes of two subarrays to be merged 9 | int n1 = m - l + 1; 10 | int n2 = r - m; 11 | 12 | /* Create temp arrays */ 13 | int L[] = new int[n1]; 14 | int R[] = new int[n2]; 15 | 16 | /*Copy data to temp arrays*/ 17 | for (int i = 0; i < n1; ++i) 18 | L[i] = arr[l + i]; 19 | for (int j = 0; j < n2; ++j) 20 | R[j] = arr[m + 1 + j]; 21 | 22 | /* Merge the temp arrays */ 23 | 24 | // Initial indexes of first and second subarrays 25 | int i = 0, j = 0; 26 | 27 | // Initial index of merged subarry array 28 | int k = l; 29 | while (i < n1 && j < n2) { 30 | if (L[i] <= R[j]) { 31 | arr[k] = L[i]; 32 | i++; 33 | } 34 | else { 35 | arr[k] = R[j]; 36 | j++; 37 | } 38 | k++; 39 | } 40 | 41 | /* Copy remaining elements of L[] if any */ 42 | while (i < n1) { 43 | arr[k] = L[i]; 44 | i++; 45 | k++; 46 | } 47 | 48 | /* Copy remaining elements of R[] if any */ 49 | while (j < n2) { 50 | arr[k] = R[j]; 51 | j++; 52 | k++; 53 | } 54 | } 55 | 56 | // Main function that sorts arr[l..r] using 57 | // merge() 58 | void sort(int arr[], int l, int r) 59 | { 60 | if (l < r) { 61 | // Find the middle point 62 | int m = (l + r) / 2; 63 | 64 | // Sort first and second halves 65 | sort(arr, l, m); 66 | sort(arr, m + 1, r); 67 | 68 | // Merge the sorted halves 69 | merge(arr, l, m, r); 70 | } 71 | } 72 | 73 | /* A utility function to print array of size n */ 74 | static void printArray(int arr[]) 75 | { 76 | int n = arr.length; 77 | for (int i = 0; i < n; ++i) 78 | System.out.print(arr[i] + " "); 79 | System.out.println(); 80 | } 81 | 82 | // Driver method 83 | public static void main(String args[]) 84 | { 85 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 86 | 87 | System.out.println("Given Array"); 88 | printArray(arr); 89 | 90 | MergeSort ob = new MergeSort(); 91 | ob.sort(arr, 0, arr.length - 1); 92 | 93 | System.out.println("\nSorted array"); 94 | printArray(arr); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /java/SelectionSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SelectionSort 4 | { 5 | public static void main(String args[]) 6 | { 7 | int size, i, j, temp; 8 | int arr[] = new int[50]; 9 | Scanner scan = new Scanner(System.in); 10 | 11 | System.out.print("Enter Array Size : "); 12 | size = scan.nextInt(); 13 | 14 | System.out.print("Enter Array Elements :"+ "(Press Enter after each): "); 15 | for(i=0; i arr[j]) 26 | { 27 | temp = arr[i]; 28 | arr[i] = arr[j]; 29 | arr[j] = temp; 30 | } 31 | } 32 | } 33 | 34 | System.out.print("Now the Array after Sorting in Incresing Order is :\n"); 35 | for(i=0; i stack) 7 | { 8 | for(int i = 0; i < 5; i++) 9 | { 10 | stack.push(i); 11 | } 12 | } 13 | 14 | // Popping element from the top of the stack 15 | static void stack_pop(Stack stack) 16 | { 17 | System.out.println("Pop Operation:"); 18 | 19 | for(int i = 0; i < 5; i++) 20 | { 21 | Integer y = (Integer) stack.pop(); 22 | System.out.println(y); 23 | } 24 | } 25 | 26 | // Displaying element on the top of the stack 27 | static void stack_peek(Stack stack) 28 | { 29 | Integer element = (Integer) stack.peek(); 30 | System.out.println("Element on stack top: " + element); 31 | } 32 | 33 | // Searching element in the stack 34 | static void stack_search(Stack stack, int element) 35 | { 36 | Integer pos = (Integer) stack.search(element); 37 | 38 | if(pos == -1) 39 | System.out.println("Element not found"); 40 | else 41 | System.out.println("Element is found at position: " + pos); 42 | } 43 | 44 | 45 | public static void main (String[] args) 46 | { 47 | Stack stack = new Stack(); 48 | 49 | stack_push(stack); 50 | stack_pop(stack); 51 | stack_push(stack); 52 | stack_peek(stack); 53 | stack_search(stack, 2); 54 | stack_search(stack, 6); 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /java/StackDemo.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.io.*; 3 | 4 | public class StackDemo { 5 | 6 | // Main Method 7 | public static void main(String args[]) 8 | { 9 | // Creating an empty Stack 10 | Stack stack = new Stack(); 11 | 12 | // Use push() to add elements into the Stack 13 | stack.push("W3Tech"); 14 | stack.push("Blog"); 15 | // Displaying the Stack 16 | System.out.println("Initial Stack: " + stack); 17 | 18 | // Fetching the element at the head of the Stack 19 | System.out.println("The element at the top of the" 20 | + " stack is: " + stack.peek()); 21 | 22 | // Displaying the Stack after the Operation 23 | System.out.println("Final Stack: " + stack); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /java/quickSort.java: -------------------------------------------------------------------------------- 1 | Quick sort in Java 2 | 3 | import java.util.Arrays; 4 | 5 | class QuickSort { 6 | 7 | // Function to partition the array on the basis of pivot element 8 | int partition(int array[], int low, int high) { 9 | 10 | // Select the pivot element 11 | int pivot = array[high]; 12 | int i = (low - 1); 13 | 14 | // Put the elements smaller than pivot on the left and 15 | // greater than pivot on the right of pivot 16 | for (int j = low; j < high; j++) { 17 | if (array[j] <= pivot) { 18 | i++; 19 | int temp = array[i]; 20 | array[i] = array[j]; 21 | array[j] = temp; 22 | } 23 | } 24 | int temp = array[i + 1]; 25 | array[i + 1] = array[high]; 26 | array[high] = temp; 27 | return (i + 1); 28 | } 29 | 30 | void quickSort(int array[], int low, int high) { 31 | if (low < high) { 32 | 33 | // Select pivot position and put all the elements smaller 34 | // than pivot on left and greater than pivot on right 35 | int pi = partition(array, low, high); 36 | 37 | // Sort the elements on the left of pivot 38 | quickSort(array, low, pi - 1); 39 | 40 | // Sort the elements on the right of pivot 41 | quickSort(array, pi + 1, high); 42 | } 43 | } 44 | 45 | // Driver code 46 | public static void main(String args[]) { 47 | int[] data = { 8, 7, 2, 1, 0, 9, 6 }; 48 | int size = data.length; 49 | QuickSort qs = new QuickSort(); 50 | qs.quickSort(data, 0, size - 1); 51 | System.out.println("Sorted Array in Ascending Order: "); 52 | System.out.println(Arrays.toString(data)); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /java/shellSort.java: -------------------------------------------------------------------------------- 1 | Shell Sort Java 2 | 3 | import java.util.Arrays; 4 | 5 | // Shell sort 6 | class ShellSort { 7 | 8 | // Rearrange elements at each n/2, n/4, n/8, ... intervals 9 | void shellSort(int array[], int n) { 10 | for (int interval = n / 2; interval > 0; interval /= 2) { 11 | for (int i = interval; i < n; i += 1) { 12 | int temp = array[i]; 13 | int j; 14 | for (j = i; j >= interval && array[j - interval] > temp; j -= interval) { 15 | array[j] = array[j - interval]; 16 | } 17 | array[j] = temp; 18 | } 19 | } 20 | } 21 | 22 | // Driver code 23 | public static void main(String args[]) { 24 | int[] data = { 9, 8, 3, 7, 5, 6, 4, 1 }; 25 | int size = data.length; 26 | ShellSort ss = new ShellSort(); 27 | ss.shellSort(data, size); 28 | System.out.println("Sorted Array in Ascending Order: "); 29 | System.out.println(Arrays.toString(data)); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /javascript/BinarySearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Binary Search 3 | * @param {number[]} nums 4 | * @param {number} target 5 | * @return {number} 6 | */ 7 | const search = (nums, target) => { 8 | return helper(nums, target, 0, nums.length - 1); 9 | }; 10 | 11 | /** 12 | * Helper Function 13 | * @param {number[]} nums 14 | * @param {number} target 15 | * @param {number} left - anchor or start 16 | * @param {number} right - end 17 | */ 18 | const helper = (nums, target, left, right) => { 19 | if (left > right) return -1; 20 | 21 | const mid = Math.floor((left + right) / 2); 22 | const check = nums[mid]; 23 | 24 | return { 25 | [true]: () => helper(nums, target, mid + 1, right), 26 | [check === target]: () => mid, 27 | [check > target]: () => helper(nums, target, left, mid - 1) 28 | }.true(); 29 | }; 30 | -------------------------------------------------------------------------------- /javascript/BubbleSort.js: -------------------------------------------------------------------------------- 1 | //Bubble sort 2 | let bubbleSort = (arr) => { 3 | //Length of the array 4 | let n = arr.length; 5 | 6 | for (let i = 0; i < n - 1; i++) { 7 | for (let j = 0; j <= n - i - 1; j++) { 8 | //Swap the numbers 9 | if (arr[j] > arr[j + 1]) { 10 | [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]]; 11 | } 12 | } 13 | } 14 | 15 | return arr; 16 | }; 17 | 18 | // Usage 19 | console.log(bubbleSort([10,9,-1,-2,0,22])); -------------------------------------------------------------------------------- /javascript/InsertionSort.js: -------------------------------------------------------------------------------- 1 | const insertionSort = (inputArr) => { 2 | let n = inputArr.length; 3 | for (let i = 1; i < n; i++) { 4 | // Choosing the first element in our unsorted subarray 5 | let current = inputArr[i]; 6 | // The last element of our sorted subarray 7 | let j = i-1; 8 | while ((j > -1) && (current < inputArr[j])) { 9 | inputArr[j+1] = inputArr[j]; 10 | j--; 11 | } 12 | inputArr[j+1] = current; 13 | } 14 | return inputArr; 15 | } 16 | // Usage 17 | let inputArr = [5, 2, 4, 6, 1, 3]; 18 | insertionSort(inputArr); 19 | console.log(inputArr); 20 | -------------------------------------------------------------------------------- /javascript/LinearSearch.js: -------------------------------------------------------------------------------- 1 | /** 2 | * @param {Array} 3 | * @param {String} 4 | * */ 5 | const linearSearch = (arr, elToFind) => { 6 | for (let i=0; i 0 && index > this.size) { 47 | return; 48 | } 49 | 50 | // If first index 51 | if (index === 0) { 52 | this.insertFirst(data); 53 | return; 54 | } 55 | 56 | const node = new Node(data); 57 | let current, previous; 58 | 59 | // Set current to first 60 | current = this.head; 61 | let count = 0; 62 | 63 | while (count < index) { 64 | previous = current; // Node before index 65 | count++; 66 | current = current.next; // Node after index 67 | } 68 | 69 | node.next = current; 70 | previous.next = node; 71 | 72 | this.size++; 73 | } 74 | 75 | // Get at index 76 | getAt(index) { 77 | let current = this.head; 78 | let count = 0; 79 | 80 | while (current) { 81 | if (count == index) { 82 | console.log(current.data); 83 | } 84 | count++; 85 | current = current.next; 86 | } 87 | 88 | return null; 89 | } 90 | 91 | // Remove at index 92 | removeAt(index) { 93 | if (index > 0 && index > this.size) { 94 | return; 95 | } 96 | 97 | let current = this.head; 98 | let previous; 99 | let count = 0; 100 | 101 | // Remove first 102 | if (index === 0) { 103 | this.head = current.next; 104 | } else { 105 | while (count < index) { 106 | count++; 107 | previous = current; 108 | current = current.next; 109 | } 110 | 111 | previous.next = current.next; 112 | } 113 | 114 | this.size--; 115 | } 116 | 117 | // Clear list 118 | clearList() { 119 | this.head = null; 120 | this.size = 0; 121 | } 122 | 123 | // Print list data 124 | printListData() { 125 | let current = this.head; 126 | 127 | while (current) { 128 | console.log(current.data); 129 | current = current.next; 130 | } 131 | } 132 | } 133 | 134 | const ll = new LinkedList(); 135 | 136 | ll.insertFirst(100); 137 | ll.insertFirst(200); 138 | ll.insertFirst(300); 139 | ll.insertLast(400); 140 | ll.insertAt(500, 3); 141 | 142 | // ll.clearList(); 143 | // ll.getAt(2); 144 | 145 | ll.printListData(); -------------------------------------------------------------------------------- /javascript/MergeSort.js: -------------------------------------------------------------------------------- 1 | //ES6 syntax 2 | //create a function to merge the arrays first 3 | const merge = (arr1, arr2) => { 4 | let sorted = []; 5 | 6 | while (arr1.length && arr2.length) { 7 | if (arr1[0] < arr2[0]) sorted.push(arr1.shift()); 8 | else sorted.push(arr2.shift()); 9 | }; 10 | 11 | return sorted.concat(arr1.slice().concat(arr2.slice())); 12 | }; 13 | 14 | //recursively merge and sort 15 | const mergeSort = arr => { 16 | if (arr.length <= 1) return arr; 17 | let mid = Math.floor(arr.length / 2), 18 | left = mergeSort(arr.slice(0, mid)), 19 | right = mergeSort(arr.slice(mid)); 20 | 21 | return merge(left, right); 22 | }; 23 | 24 | //test case 25 | let unsortedArr = [1,23,4,5,6,32,2,4,12,3,5,25,3,5,1,23,4,5,6,32,2,4,12,3,5,25,3,5,1,23,4,5,6,32,2,4,12,3,5,25,3,5]; 26 | 27 | //output: [1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 12, 12, 12, 23, 23, 23, 25, 25, 25, 32, 32, 32] 28 | console.log(mergeSort(unsortedArr)); 29 | -------------------------------------------------------------------------------- /javascript/SelectionSort.js: -------------------------------------------------------------------------------- 1 | let selectionSort = (arr) => { 2 | let len = arr.length; 3 | for (let i = 0; i < len; i++) { 4 | let min = i; 5 | for (let j = i + 1; j < len; j++) { 6 | if (arr[min] > arr[j]) { 7 | min = j; 8 | } 9 | } 10 | if (min !== i) { 11 | let tmp = arr[i]; 12 | arr[i] = arr[min]; 13 | arr[min] = tmp; 14 | } 15 | } 16 | return arr; 17 | } 18 | 19 | // Usage 20 | let inputArr = [5, 2, 4, 6, 1, 3]; 21 | selectionSort(inputArr); 22 | console.log(inputArr); 23 | -------------------------------------------------------------------------------- /javascript/Stack.js: -------------------------------------------------------------------------------- 1 | 2 | class Stack { 3 | constructor() { 4 | this.items = [] 5 | this.count = 0 6 | } 7 | 8 | // Add element to top of stack 9 | push(element) { 10 | this.items[this.count] = element 11 | console.log(`${element} added to ${this.count}`) 12 | this.count += 1 13 | return this.count - 1 14 | } 15 | 16 | // Return and remove top element in stack 17 | // Return undefined if stack is empty 18 | pop() { 19 | if(this.count == 0) return undefined 20 | let deleteItem = this.items[this.count - 1] 21 | this.count -= 1 22 | console.log(`${deleteItem} removed`) 23 | return deleteItem 24 | } 25 | 26 | // Check top element in stack 27 | peek() { 28 | console.log(`Top element is ${this.items[this.count - 1]}`) 29 | return this.items[this.count - 1] 30 | } 31 | 32 | // Check if stack is empty 33 | isEmpty() { 34 | console.log(this.count == 0 ? 'Stack is empty' : 'Stack is NOT empty') 35 | return this.count == 0 36 | } 37 | 38 | // Check size of stack 39 | size() { 40 | console.log(`${this.count} elements in stack`) 41 | return this.count 42 | } 43 | 44 | // Print elements in stack 45 | print() { 46 | let str = '' 47 | for(let i = 0; i < this.count; i++) { 48 | str += this.items[i] + ' ' 49 | } 50 | return str 51 | } 52 | 53 | // Clear stack 54 | clear() { 55 | this.items = [] 56 | this.count = 0 57 | console.log('Stack cleared..') 58 | return this.items 59 | } 60 | } 61 | 62 | const stack = new Stack() 63 | 64 | stack.isEmpty() 65 | 66 | stack.push(100) 67 | stack.push(200) 68 | 69 | stack.peek() 70 | 71 | stack.push(300) 72 | 73 | console.log(stack.print()) 74 | 75 | stack.pop() 76 | stack.pop() 77 | 78 | stack.clear() 79 | 80 | console.log(stack.print()) 81 | 82 | stack.size() 83 | 84 | stack.isEmpty() 85 | -------------------------------------------------------------------------------- /python/BinarySearch.py: -------------------------------------------------------------------------------- 1 | # Returns index of x in arr if present, else -1 2 | def binarySearch (arr, l, r, x): 3 | 4 | # Check base case 5 | if r >= l: 6 | 7 | mid = l + (r - l) // 2 8 | 9 | # If element is present at the middle itself 10 | if arr[mid] == x: 11 | return mid 12 | 13 | # If element is smaller than mid, then it 14 | # can only be present in left subarray 15 | elif arr[mid] > x: 16 | return binarySearch(arr, l, mid-1, x) 17 | 18 | # Else the element can only be present 19 | # in right subarray 20 | else: 21 | return binarySearch(arr, mid + 1, r, x) 22 | 23 | else: 24 | # Element is not present in the array 25 | return -1 26 | 27 | # Driver Code 28 | arr = [ 2, 3, 4, 10, 40 ] 29 | x = 10 30 | 31 | # Usage 32 | result = binarySearch(arr, 0, len(arr)-1, x) 33 | 34 | if result != -1: 35 | print ("Element is present at index % d" % result) 36 | else: 37 | print ("Element is not present in array") 38 | -------------------------------------------------------------------------------- /python/BubbleSort.py: -------------------------------------------------------------------------------- 1 | # @author Yash Karanke 2 | def bubbleSort(nlist): 3 | for passnum in range(len(nlist)-1,0,-1): 4 | for i in range(passnum): 5 | if nlist[i]>nlist[i+1]: 6 | temp = nlist[i] 7 | nlist[i] = nlist[i+1] 8 | nlist[i+1] = temp 9 | 10 | nlist = [14,46,43,27,57,41,45,21,70] 11 | bubbleSort(nlist) 12 | print(nlist) 13 | -------------------------------------------------------------------------------- /python/CountingSort.py: -------------------------------------------------------------------------------- 1 | def count_sort(arr): 2 | max_element = int(max(arr)) 3 | min_element = int(min(arr)) 4 | range_of_elements = max_element - min_element + 1 5 | # Create a count array to store count of individual 6 | # elements and initialize count array as 0 7 | count_arr = [0 for _ in range(range_of_elements)] 8 | output_arr = [0 for _ in range(len(arr))] 9 | 10 | # Store count of each character 11 | for i in range(0, len(arr)): 12 | count_arr[arr[i]-min_element] += 1 13 | 14 | # Change count_arr[i] so that count_arr[i] now contains actual 15 | # position of this element in output array 16 | for i in range(1, len(count_arr)): 17 | count_arr[i] += count_arr[i-1] 18 | 19 | # Build the output character array 20 | for i in range(len(arr)-1, -1, -1): 21 | output_arr[count_arr[arr[i] - min_element] - 1] = arr[i] 22 | count_arr[arr[i] - min_element] -= 1 23 | 24 | # Copy the output array to arr, so that arr now 25 | # contains sorted characters 26 | for i in range(0, len(arr)): 27 | arr[i] = output_arr[i] 28 | 29 | return arr 30 | 31 | 32 | # Driver program to test above function 33 | arr = [-5, -10, 0, -3, 8, 5, -1, 10] 34 | ans = count_sort(arr) 35 | print("Sorted character array is " + str(ans)) 36 | -------------------------------------------------------------------------------- /python/HeapSort.py: -------------------------------------------------------------------------------- 1 | def heapify(arr, n, i): 2 | largest = i # Initialize largest as root 3 | l = 2 * i + 1 # left = 2*i + 1 4 | r = 2 * i + 2 # right = 2*i + 2 5 | 6 | # See if left child of root exists and is 7 | # greater than root 8 | if l < n and arr[i] < arr[l]: 9 | largest = l 10 | 11 | # See if right child of root exists and is 12 | # greater than root 13 | if r < n and arr[largest] < arr[r]: 14 | largest = r 15 | 16 | # Change root, if needed 17 | if largest != i: 18 | arr[i], arr[largest] = arr[largest], arr[i] # swap 19 | 20 | # Heapify the root. 21 | heapify(arr, n, largest) 22 | 23 | # The main function to sort an array of given size 24 | 25 | 26 | def heapSort(arr): 27 | n = len(arr) 28 | 29 | # Build a maxheap. 30 | # Since last parent will be at ((n//2)-1) we can start at that location. 31 | for i in range(n // 2 - 1, -1, -1): 32 | heapify(arr, n, i) 33 | 34 | # One by one extract elements 35 | for i in range(n-1, 0, -1): 36 | arr[i], arr[0] = arr[0], arr[i] # swap 37 | heapify(arr, i, 0) 38 | 39 | 40 | # Driver code to test above 41 | arr = [12, 11, 13, 5, 6, 7] 42 | heapSort(arr) 43 | n = len(arr) 44 | print("Sorted array is") 45 | for i in range(n): 46 | print("%d" % arr[i]), 47 | -------------------------------------------------------------------------------- /python/InsertionSort.py: -------------------------------------------------------------------------------- 1 | def insertion_sort(arr): 2 | comparisons = 0 3 | moves = 0 4 | 5 | for step in range(1,len(arr)): 6 | key = arr[step] 7 | i = step - 1 8 | 9 | while i >= 0 and key < arr[i]: 10 | arr[i + 1] = arr[i] 11 | i = i - 1 12 | comparisons += 1 13 | 14 | if arr[i + 1] != key: 15 | arr[i + 1] = key 16 | print(arr) 17 | moves += 1 18 | return (comparisons, moves) 19 | 20 | data = [6,2,4,3,5,1,7] 21 | comparisons, moves = insertion_sort(data) 22 | print(f'Sorted Array in Ascending Order: {data}') 23 | print(f'Sorted in {moves} moves and {comparisons} comparisons') 24 | 25 | 26 | # Sample input [6,2,4,3,5,1,7] 27 | # Sample Output 28 | # [2, 6, 4, 3, 5, 1, 7] 29 | # [2, 4, 6, 3, 5, 1, 7] 30 | # [2, 3, 4, 6, 5, 1, 7] 31 | # [2, 3, 4, 5, 6, 1, 7] 32 | # [1, 2, 3, 4, 5, 6, 7] 33 | # Sorted Array in Ascending Order: [1, 2, 3, 4, 5, 6, 7] 34 | # Sorted in 5 moves and 10 comparisons 35 | 36 | # Space Complexity: O(n) 37 | 38 | # Time complexity 39 | # Worst case: O(n^2) 40 | # Best case: O(n) 41 | # Average case: O(n^2) 42 | -------------------------------------------------------------------------------- /python/LinearSearch.py: -------------------------------------------------------------------------------- 1 | def linearsearch(arr, x): 2 | for i in range(len(arr)): 3 | if arr[i] == x: 4 | return i 5 | return -1 6 | # Usage 7 | arr = ['y','a','s','h'] 8 | x = 'a' 9 | print("element found at index "+str(linearsearch(arr,x))) 10 | -------------------------------------------------------------------------------- /python/LinkedList.py: -------------------------------------------------------------------------------- 1 | class Node: 2 | 3 | # Function to initialise the node object 4 | def __init__(self, data): 5 | self.data = data # Assign data 6 | self.next = None # Initialize next as null 7 | 8 | 9 | # Linked List class contains a Node object 10 | class LinkedList: 11 | 12 | # Function to initialize head 13 | def __init__(self): 14 | self.head = None 15 | 16 | # This function prints contents of linked list 17 | # starting from head 18 | def printList(self): 19 | temp = self.head 20 | while (temp): 21 | print(temp.data) 22 | temp = temp.next 23 | 24 | 25 | # Code execution starts here 26 | if __name__ == '__main__': 27 | 28 | # Start with the empty list 29 | llist = LinkedList() 30 | 31 | llist.head = Node(1) 32 | second = Node(2) 33 | third = Node(3) 34 | 35 | llist.head.next = second # Link first node with second 36 | second.next = third # Link second node with the third node 37 | 38 | llist.printList() 39 | -------------------------------------------------------------------------------- /python/MergeSort.py: -------------------------------------------------------------------------------- 1 | def merge(arr, L, R): 2 | i = j = k = 0 3 | 4 | # Copy data to temp arrays L[] and R[] 5 | while i < len(L) and j < len(R): 6 | if L[i] < R[j]: 7 | arr[k] = L[i] 8 | i+= 1 9 | else: 10 | arr[k] = R[j] 11 | j+= 1 12 | k+= 1 13 | 14 | # Checking if any element was left 15 | while i < len(L): 16 | arr[k] = L[i] 17 | i+= 1 18 | k+= 1 19 | 20 | while j < len(R): 21 | arr[k] = R[j] 22 | j+= 1 23 | k+= 1 24 | 25 | def mergeSort(arr): 26 | if len(arr) > 1: 27 | mid = len(arr)//2 # Finding the mid of the array 28 | L = arr[:mid] # Dividing the array elements into 2 halves 29 | R = arr[mid:] 30 | 31 | mergeSort(L) # Sorting the first half 32 | mergeSort(R) # Sorting the second half 33 | merge(arr, L, R) # Merging the 2 halves 34 | 35 | 36 | # Code to print the list 37 | def printList(arr): 38 | for i in range(len(arr)): 39 | print(arr[i], end =" ") 40 | print() 41 | 42 | # driver code to test the above code 43 | if __name__ == '__main__': 44 | arr = [1,23,4,5,6,32,2,4,12,3,5,25,3,5,1,23,4,5,6,32,2,4,12,3,5,25,3,5,1,23,4,5,6,32,2,4,12,3,5,25,3,5]; 45 | print ("Given array is", end ="\n") 46 | printList(arr) 47 | mergeSort(arr) 48 | print("Sorted array is: ", end ="\n") 49 | printList(arr) -------------------------------------------------------------------------------- /python/NumberSort.py: -------------------------------------------------------------------------------- 1 | def sortSecond(val): 2 | return val[1] 3 | 4 | 5 | # list1 to demonstrate the use of sorting 6 | # using using second key 7 | list1 = [(1, 2), (3, 3), (1, 1)] 8 | 9 | # sorts the array in ascending according to 10 | # second element 11 | list1.sort(key=sortSecond) 12 | print(list1) 13 | 14 | # sorts the array in descending according to 15 | # second element 16 | list1.sort(key=sortSecond, reverse=True) 17 | print(list1) 18 | -------------------------------------------------------------------------------- /python/breadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | import collections 2 | class graph: 3 | def __init__(self,gdict=None): 4 | if gdict is None: 5 | gdict = {} 6 | self.gdict = gdict 7 | 8 | def bfs(graph, startnode): 9 | # Track the visited and unvisited nodes using queue 10 | seen, queue = set([startnode]), collections.deque([startnode]) 11 | while queue: 12 | vertex = queue.popleft() 13 | marked(vertex) 14 | for node in graph[vertex]: 15 | if node not in seen: 16 | seen.add(node) 17 | queue.append(node) 18 | 19 | def marked(n): 20 | print(n) 21 | 22 | # The graph dictionary 23 | gdict = { "a" : set(["b","c"]), 24 | "b" : set(["a", "d"]), 25 | "c" : set(["a", "d"]), 26 | "d" : set(["e"]), 27 | "e" : set(["a"]) 28 | } 29 | 30 | bfs(gdict, "a") -------------------------------------------------------------------------------- /python/bucketSort.py: -------------------------------------------------------------------------------- 1 | Bucket Sort Python 2 | 3 | def bucketSort(array): 4 | bucket = [] 5 | 6 | # Create empty buckets 7 | for i in range(len(array)): 8 | bucket.append([]) 9 | 10 | # Insert elements into their respective buckets 11 | for j in array: 12 | index_b = int(10 * j) 13 | bucket[index_b].append(j) 14 | 15 | # Sort the elements of each bucket 16 | for i in range(len(array)): 17 | bucket[i] = sorted(bucket[i]) 18 | 19 | # Get the sorted elements 20 | k = 0 21 | for i in range(len(array)): 22 | for j in range(len(bucket[i])): 23 | array[k] = bucket[i][j] 24 | k += 1 25 | return array 26 | 27 | 28 | array = [.42, .32, .33, .52, .37, .47, .51] 29 | print("Sorted Array in descending order is") 30 | print(bucketSort(array)) 31 | -------------------------------------------------------------------------------- /python/depthFirstSearch.py: -------------------------------------------------------------------------------- 1 | class graph: 2 | 3 | def __init__(self,gdict=None): 4 | if gdict is None: 5 | gdict = {} 6 | self.gdict = gdict 7 | # Check for the visisted and unvisited nodes 8 | def dfs(graph, start, visited = None): 9 | if visited is None: 10 | visited = set() 11 | visited.add(start) 12 | print(start) 13 | for next in graph[start] - visited: 14 | dfs(graph, next, visited) 15 | return visited 16 | 17 | gdict = { "a" : set(["b","c"]), 18 | "b" : set(["a", "d"]), 19 | "c" : set(["a", "d"]), 20 | "d" : set(["e"]), 21 | "e" : set(["a"]) 22 | } 23 | 24 | 25 | dfs(gdict, 'a') -------------------------------------------------------------------------------- /python/selectionSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Selection Sort 2 | 3 | arr = [98, 12, 89, 2, 84] 4 | 5 | for i in range(len(arr)): 6 | min_idx = i 7 | for j in range(i+1, len(arr)): 8 | if arr[min_idx] > arr[j]: 9 | min_idx = j 10 | 11 | arr[i], arr[min_idx] = arr[min_idx], arr[i] 12 | 13 | for i in range(len(arr)): 14 | print(arr[i]) 15 | -------------------------------------------------------------------------------- /rust/BinarySearch.rs: -------------------------------------------------------------------------------- 1 | fn binary_search(vec: Vec, key: T) -> Option { 2 | let mut high: usize = vec.len() - 1; 3 | let mut low: usize = 0; 4 | let mut middle: usize; 5 | 6 | while low <= high { 7 | middle = (high + low) / 2; 8 | 9 | if key == vec[middle] { 10 | return Some(middle); 11 | } 12 | if key > vec[middle] { 13 | low = middle + 1; 14 | } 15 | else { 16 | high = middle - 1; 17 | } 18 | } 19 | 20 | None 21 | } 22 | 23 | fn main() { 24 | let mut vec = vec![3,5,4,1,6,4,7,9,1]; 25 | vec.sort_unstable(); 26 | println!("{:?}", vec); 27 | match binary_search(vec, 5) { 28 | Some(i) => println!("{:?}", i), 29 | None => println!("Not found!") 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /rust/BubbleSort.rs: -------------------------------------------------------------------------------- 1 | enum Sort { 2 | Ascending, 3 | Descending 4 | } 5 | 6 | fn bubble_sort(arr: &mut [T], sort: Sort) { 7 | let length = arr.len(); 8 | 9 | match sort { 10 | Sort::Ascending => { 11 | for i in 0..length-1 { 12 | for j in 0..length-i-1 { 13 | if arr[j] > arr[j+1] { 14 | arr.swap(j, j+1); 15 | } 16 | } 17 | } 18 | }, 19 | Sort::Descending => { 20 | for i in 0..length-1 { 21 | for j in 0..length-i-1 { 22 | if arr[j] < arr[j+1] { 23 | arr.swap(j, j+1); 24 | } 25 | } 26 | } 27 | } 28 | } 29 | 30 | } 31 | 32 | fn main() { 33 | let mut vec = vec![1,4,3,6,1,3,5,2]; 34 | println!("Before sorting: {:?}", vec); 35 | bubble_sort(&mut vec, Sort::Ascending); 36 | println!("Sorted ascending: {:?}", vec); 37 | bubble_sort(&mut vec, Sort::Descending); 38 | println!("Sorted descending: {:?}", vec); 39 | } 40 | -------------------------------------------------------------------------------- /rust/Queue.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Queue(Vec); 3 | 4 | impl Queue { 5 | fn new() -> Queue { 6 | Queue(Vec::::new()) 7 | } 8 | fn enqueue(&mut self, item: T) { 9 | self.0.push(item); 10 | } 11 | fn dequeue(&mut self) { 12 | if !self.0.is_empty() { 13 | self.0.remove(0); 14 | } 15 | } 16 | fn length(&self) -> usize { 17 | self.0.len() 18 | } 19 | } 20 | 21 | fn main() { 22 | let mut queue = Queue::<&str>::new(); 23 | queue.enqueue("T"); 24 | println!("{:?}", queue); 25 | println!("Length of the queue is: {}", queue.length()); 26 | queue.dequeue(); 27 | println!("{:?}", queue); 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn queue_enqueue() { 36 | let mut queue = Queue::::new(); 37 | queue.enqueue(5); 38 | assert_eq!(queue.0, vec![5]); 39 | } 40 | 41 | #[test] 42 | fn queue_dequeue() { 43 | let mut queue = Queue::::new(); 44 | queue.enqueue(5); 45 | queue.dequeue(); 46 | assert_eq!(queue.0, vec![]); 47 | } 48 | 49 | #[test] 50 | fn queue_length() { 51 | let mut queue = Queue::::new(); 52 | queue.enqueue(5); 53 | queue.enqueue(59); 54 | assert_eq!(queue.length(), 2); 55 | } 56 | } -------------------------------------------------------------------------------- /rust/Stack.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | struct Stack(Vec); 3 | 4 | impl Stack { 5 | fn new() -> Stack { 6 | Stack(Vec::::new()) 7 | } 8 | fn push(&mut self, item: T) { 9 | self.0.push(item); 10 | } 11 | fn pop(&mut self) { 12 | self.0.pop(); 13 | } 14 | fn length(&self) -> usize { 15 | self.0.len() 16 | } 17 | } 18 | 19 | fn main() { 20 | let mut stack = Stack::<&str>::new(); 21 | stack.push("T"); 22 | println!("{:?}", stack); 23 | stack.push("A"); 24 | println!("{:?}", stack); 25 | println!("Length is {}", stack.length()); 26 | stack.pop(); 27 | println!("{:?}", stack); 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | 34 | #[test] 35 | fn stack_push() { 36 | let mut stack = Stack::::new(); 37 | stack.push(5); 38 | assert_eq!(stack.0, vec![5]); 39 | } 40 | 41 | #[test] 42 | fn stack_pop() { 43 | let mut stack = Stack::::new(); 44 | stack.push(5); 45 | stack.pop(); 46 | assert_eq!(stack.0, vec![]); 47 | } 48 | 49 | #[test] 50 | fn stack_length() { 51 | let mut stack = Stack::::new(); 52 | stack.push(5); 53 | stack.push(59); 54 | assert_eq!(stack.length(), 2); 55 | } 56 | } 57 | --------------------------------------------------------------------------------