├── .gitignore ├── C ├── Data_structures │ ├── Hashtable.c │ ├── Linear_List.c │ ├── Queue.c │ ├── Stack.c │ ├── binary_search_tree.c │ └── linkedlist.c ├── Search │ └── binary_search.c ├── Sorting_algorithms │ ├── bubble_sort.c │ ├── heapsort.c │ ├── insertion_sort.c │ ├── merge_sort.c │ ├── quick_sort.c │ └── selection_sort.c └── radix_sort.c ├── R └── Search │ └── linear_search.R ├── README.md ├── Rust └── Sorts │ ├── bubblesort.rs │ └── insertionsort.rs ├── c# ├── Data_structures │ └── Trie.cs └── Sorting_algorithms │ └── merge_sort.cs ├── clojure ├── README.md └── Search │ └── binary_chop.clj ├── cpp ├── BST.cpp ├── Data_structures │ ├── Dial_algorithm.cpp │ ├── Stack.cpp │ ├── all_pair_shortest_path.cpp │ ├── bfs.cpp │ ├── bfs_recursive.cpp │ ├── bicolorable_graph.cpp │ ├── counting_inversion.cpp │ ├── cpp-boilerplate.cpp │ ├── dfs.cpp │ ├── dfs_recursive.cpp │ ├── heap.cpp │ ├── intersection.cpp │ ├── linear_search.cpp │ ├── middle_element_in_linkedlist.cpp │ ├── modular_inverse.cpp │ └── reverse_a_linkedlist.cpp ├── InterpolationSearch.cpp ├── Search │ └── binary_search.cpp ├── Sorting_algorithms │ ├── HeapSort.cpp │ ├── bubbleSort.cpp │ ├── bubble_sort.h │ ├── insertion_sort.cpp │ ├── insertion_sort_recursive.cpp │ ├── merge_sort.h │ ├── merge_sorted_linkedlists │ ├── merging.cpp │ ├── quick_sort.h │ ├── radixsort.cpp │ ├── selection_sort.cpp │ └── selection_sort_recursive.cpp ├── detect_loop_linked_list.cpp ├── jump_search.cpp └── kadane_maxSum_of_subarray.cpp ├── erlang ├── Data_structures │ └── forkjoin.erl ├── README.md └── Sorting_algorithm │ ├── pqsort.erl │ └── quicksort.erl ├── go └── algs │ ├── Data_structures │ └── linked-list.go │ ├── Search │ └── search.go │ └── Sorting_algorithm │ ├── Bubblesort.go │ └── mergeshort.go ├── haskell └── factorial.hs ├── java ├── Data Structures │ ├── DoublyLinkedList.java │ ├── GenericTree.java │ ├── Graphs.java │ ├── HashMap.java │ ├── Heap.java │ ├── MaxPriorityQueue.java │ ├── MinPriorityQueue.java │ ├── Minimum_Spanning_tree.java │ ├── PriorityQueue.java │ ├── SegmentTree.java │ ├── SinglyLinkedList.java │ ├── Stack.java │ ├── Tries.java │ ├── binary_search_tree.java │ ├── binary_tree.java │ ├── generic_linked_list.java │ └── queue.java ├── Fibonacci.java ├── FibonnaciDP.java ├── FloydAlgo.java ├── GreatestCommonDivisor.java ├── PalindromeNumber.java ├── PrimeNumber.java ├── PrintArmstrongNo.java ├── Remove Stop Words in given text file │ ├── StopWords.java │ └── test.txt ├── Search │ ├── BitonicSearch.java │ ├── IntArrayLinearSearch.java │ ├── RecursiveBinarySearch.java │ ├── binary_search.java │ ├── jumpsearch.java │ ├── linear_search(string).java │ └── linear_search.java └── Sorts │ ├── Bubble_and_Linear_sort.java │ ├── Bucket.java │ ├── CountSort.java │ ├── HeapSort.java │ ├── InsertionSortGenerics.java │ ├── SelectionSort.java │ ├── TopologicalSort.java │ ├── bubble_sort.java │ ├── insertion_sort.java │ ├── merge_sort.java │ ├── merge_sort_any.java │ ├── quick_sort.java │ └── selection_sort.java ├── javascript ├── Data_structures │ └── queue.js ├── Search │ └── binary_search.js ├── Sorting_algorithms │ ├── bubble_sort.js │ ├── insertion_sort.js │ ├── merge_sort.js │ ├── quicksort.js │ ├── selection_sort.js │ └── shellsort.js ├── array.js ├── binary_search.js ├── bubble_sort.js ├── greatest_common_divisor.js ├── insertion_sort.js ├── merge_sort.js ├── queue.js ├── quicksort.js ├── selection_sort.js └── shellsort.js ├── kotlin ├── Search │ ├── binarysearch.kt │ └── linearsearch.kt └── fibonacci.kt ├── php ├── Search │ └── binary_search.php └── Sorting_algorithm │ └── insertion_sort.php ├── python ├── Backtracking │ ├── binary_string.py │ ├── coin_denom.py │ ├── n_queen.py │ └── string_permutations.py ├── Data_structures │ ├── BinarySearchTree.py │ ├── BreadthFirstSearch.py │ ├── Depth-First _Search_Recursive_Function.py │ ├── kruskal.py │ ├── optimization.py │ ├── search.py │ └── stack.py ├── README.md ├── Search │ ├── BinarySearchTree.py │ ├── BreadthFirstSearch.py │ ├── Depth-First _Search_Recursive_Function.py │ └── search.py ├── Sorts │ ├── bubble_sort.py │ ├── merge_sort.py │ ├── mergesort.py │ ├── quick_sort.py │ ├── quicksort.py │ ├── radix_sort │ ├── selection_sort.py │ ├── shell_sort.py │ └── sleep_sort.py └── binomial_coefficients.py ├── ruby ├── Search │ └── linear_search.ruby └── Sorting_algorithms │ ├── bubble_sort.rb │ └── merge_sort.rb └── scala ├── Search └── linear_search.scala └── Sorting_algorithms └── quicksort.scala /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/linux,macos,windows,visualstudiocode 3 | 4 | ### Linux ### 5 | *~ 6 | 7 | # temporary files which can be created if a process still has a handle open of a deleted file 8 | .fuse_hidden* 9 | 10 | # KDE directory preferences 11 | .directory 12 | 13 | # Linux trash folder which might appear on any partition or disk 14 | .Trash-* 15 | 16 | # .nfs files are created when an open file is removed but is still being accessed 17 | .nfs* 18 | 19 | ### macOS ### 20 | *.DS_Store 21 | .AppleDouble 22 | .LSOverride 23 | 24 | # Icon must end with two \r 25 | Icon 26 | 27 | # Thumbnails 28 | ._* 29 | 30 | # Files that might appear in the root of a volume 31 | .DocumentRevisions-V100 32 | .fseventsd 33 | .Spotlight-V100 34 | .TemporaryItems 35 | .Trashes 36 | .VolumeIcon.icns 37 | .com.apple.timemachine.donotpresent 38 | 39 | # Directories potentially created on remote AFP share 40 | .AppleDB 41 | .AppleDesktop 42 | Network Trash Folder 43 | Temporary Items 44 | .apdisk 45 | 46 | ### VisualStudioCode ### 47 | .vscode/* 48 | !.vscode/settings.json 49 | !.vscode/tasks.json 50 | !.vscode/launch.json 51 | !.vscode/extensions.json 52 | .history 53 | 54 | ### Windows ### 55 | # Windows thumbnail cache files 56 | Thumbs.db 57 | ehthumbs.db 58 | ehthumbs_vista.db 59 | 60 | # Folder config file 61 | Desktop.ini 62 | 63 | # Recycle Bin used on file shares 64 | $RECYCLE.BIN/ 65 | 66 | # Windows Installer files 67 | *.cab 68 | *.msi 69 | *.msm 70 | *.msp 71 | 72 | # Windows shortcuts 73 | *.lnk 74 | 75 | # End of https://www.gitignore.io/api/linux,macos,windows,visualstudiocode 76 | -------------------------------------------------------------------------------- /C/Data_structures/Linear_List.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yshshrm/Algorithms-And-Data-Structures/23a4e980f9dacce2c9624f50391bf60832f83908/C/Data_structures/Linear_List.c -------------------------------------------------------------------------------- /C/Data_structures/Queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | 5 | typedef struct node* pointer; 6 | 7 | typedef struct Item{ 8 | int key; 9 | }Item; 10 | 11 | typedef struct node{ 12 | pointer next; 13 | Item item; 14 | }node; 15 | 16 | typedef struct Queue{ 17 | pointer end; 18 | }Queue; 19 | //Starts the Queue 20 | void StartQueue(Queue* queue){ 21 | queue->end = NULL; 22 | } 23 | //Add a element on the Queue Back 24 | int Add(Queue* queue, Item item){ 25 | if(queue == NULL) 26 | return 0; 27 | 28 | if(queue->end == NULL){ 29 | queue->end = (pointer) malloc(sizeof(node)); 30 | queue->end->item = item; 31 | queue->end->next = NULL; 32 | return 1; 33 | } 34 | else{ 35 | pointer aux = (pointer) malloc(sizeof(node)); 36 | aux->item=item; 37 | aux->next = queue->end; 38 | queue->end = aux; 39 | return 1; 40 | } 41 | 42 | } 43 | //Remove the Queue front 44 | int Remove(Queue* queue){ 45 | if(queue == NULL) 46 | return 0; 47 | pointer front=queue->end; 48 | pointer that = NULL; 49 | while(front->next!=NULL){ 50 | that = front; 51 | front = front->next; 52 | } 53 | free(front); 54 | if(that!=NULL) 55 | that->next = NULL; 56 | return 1; 57 | } 58 | 59 | //Shows the Queue 60 | void PrintQueue(Queue* queue){ 61 | if (queue == NULL){ 62 | printf("empty\n"); 63 | } 64 | pointer aux = queue->end ; 65 | while(aux!=NULL){ 66 | printf("%d \n", aux->item.key); 67 | aux = aux->next; 68 | } 69 | } 70 | 71 | -------------------------------------------------------------------------------- /C/Data_structures/Stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef struct tipo_info{ 5 | int numero; 6 | }tipo_info; 7 | 8 | typedef struct item{ 9 | tipo_info info; 10 | struct item *proximo; 11 | }tipo_item; 12 | //Pilha Means Stack, in portugues '-' 13 | typedef struct pilha{ 14 | tipo_item *topo; 15 | }tipo_pilha; 16 | //creat the Stack 17 | void cria_pilha(tipo_pilha *pilha){ 18 | pilha->topo = NULL; 19 | } 20 | //test if the stack is empty 21 | short pilha_vazia(tipo_pilha *pilha){ 22 | return (pilha->topo == NULL); 23 | } 24 | //aux to push 25 | tipo_item* pilha_alloc(tipo_info info){ 26 | tipo_item *novo = (tipo_item*) malloc(sizeof(tipo_item)); 27 | novo->proximo = NULL; 28 | novo->info = info; 29 | return novo; 30 | } 31 | //add a element at the top 32 | void push(tipo_pilha *pilha, tipo_info info){ 33 | tipo_item *novo, *aux; 34 | 35 | novo = pilha_alloc(info); 36 | 37 | if(pilha->topo == NULL){ 38 | pilha->topo = novo; 39 | return; 40 | } 41 | aux = pilha->topo; 42 | pilha->topo = novo; 43 | pilha->topo->proximo = aux; 44 | 45 | } 46 | //Remove the top element 47 | tipo_info pop(tipo_pilha *pilha){ 48 | tipo_item *aux; 49 | 50 | if(pilha_vazia(pilha)){ 51 | aux->info.numero = -1; 52 | return aux->info; 53 | } 54 | 55 | aux = pilha->topo; 56 | pilha->topo = pilha->topo->proximo; 57 | tipo_info info = aux->info; 58 | free(aux); 59 | return info; 60 | } 61 | //Show the stack 62 | void print_Stack(tipo_pilha *pilha){ 63 | tipo_item *aux; 64 | 65 | aux = pilha->topo; 66 | 67 | while(aux != NULL){ 68 | printf("%d\n",aux->info.numero); 69 | aux= aux->proximo; 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /C/Data_structures/binary_search_tree.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | typedef struct No* arvbin; 4 | typedef struct Info{ 5 | int valor; 6 | }Info; 7 | 8 | struct No{ 9 | struct No *dir; 10 | struct No *esq; 11 | Info info; 12 | }; 13 | 14 | arvbin* cria(); 15 | int Push(Info info, arvbin* raiz); 16 | 17 | arvbin* cria(){ 18 | arvbin* novo; 19 | novo = (arvbin*) malloc(sizeof(arvbin)); 20 | if(novo!=NULL){ 21 | *novo = NULL; 22 | return novo; 23 | } 24 | else return NULL; 25 | } 26 | 27 | int Push(Info info, arvbin* raiz){ 28 | arvbin novo = (arvbin) malloc(sizeof(struct No)); 29 | novo->info = info; 30 | novo->dir = NULL; 31 | novo->esq = NULL; 32 | if(*raiz == NULL){ 33 | *raiz = novo; 34 | // printf("1 elemento add\n"); 35 | return 1; 36 | } 37 | else{ 38 | arvbin ant = NULL; 39 | arvbin atual = *raiz; 40 | while(atual!=NULL){ 41 | ant=atual; 42 | if(info.valor == atual->info.valor){ 43 | // printf("Valor repetido"); 44 | free(novo); 45 | return 0; 46 | } 47 | else if(info.valor > atual->info.valor){ 48 | // ant = atual; 49 | atual = atual->dir; 50 | } 51 | 52 | else{ 53 | // ant=atual; 54 | atual = atual->esq; 55 | } 56 | 57 | } 58 | // printf("saiu do loop\n"); 59 | if(info.valor >ant->info.valor) 60 | ant->dir = novo; 61 | 62 | else 63 | ant->esq = novo; 64 | 65 | } 66 | return 1; 67 | } 68 | 69 | void DestroiNo(arvbin no){ 70 | if(no == NULL) return; 71 | DestroiNo(no->dir); 72 | DestroiNo(no->esq); 73 | free(no); 74 | no = NULL; 75 | } 76 | 77 | void DestroiArv(arvbin* raiz){ 78 | if(raiz == NULL) return; 79 | DestroiNo(*raiz); 80 | free(raiz); 81 | raiz = NULL; 82 | } 83 | 84 | 85 | void ImprimirNo(arvbin no){ 86 | if(no==NULL){ 87 | //printf("\n"); 88 | return; 89 | } 90 | 91 | printf(" %d \n", no->info.valor); 92 | //printf("dir\n"); 93 | ImprimirNo(no->dir); 94 | // printf("esq\n"); 95 | ImprimirNo(no->esq); 96 | } 97 | 98 | void ImprimirArv(arvbin* raiz){ 99 | if(raiz == NULL){ 100 | printf("\n"); 101 | return; 102 | } 103 | ImprimirNo(*raiz); 104 | } 105 | 106 | int ArvVazia(arvbin* arv){ 107 | return(*arv == NULL); 108 | } 109 | 110 | int NumNo(arvbin no){ 111 | if(no != NULL) 112 | return 1 + NumNo(no->esq) + NumNo(no->dir); 113 | if(no==NULL) 114 | return 0; 115 | // NumNo(no->esq); 116 | // NumNo(no->dir); 117 | } 118 | 119 | 120 | 121 | int altura(arvbin* raiz){ 122 | if(raiz == NULL){ 123 | return 0; 124 | } 125 | if(*raiz == NULL) 126 | return 0; 127 | 128 | int alt_esq = altura(&((*raiz)->esq)); 129 | int alt_dir = altura(&((*raiz)->dir)); 130 | if(alt_esq >= alt_dir){ 131 | return 1 + alt_esq; 132 | } 133 | else 134 | return 1+alt_dir; 135 | } 136 | 137 | 138 | arvbin BuscaLinear(arvbin* raiz,Info info){ 139 | if(raiz == NULL || *raiz == NULL) 140 | return NULL; 141 | 142 | arvbin No = *raiz; 143 | while(No!=NULL){ 144 | if(No->info.valor == info.valor) 145 | break; 146 | 147 | if(info.valor > No->info.valor) 148 | No = No->dir; 149 | else 150 | No = No->esq; 151 | } 152 | return No; 153 | } 154 | 155 | arvbin BuscaRecursiva(arvbin* raiz,Info info){ 156 | if((*raiz)->info.valor == info.valor ){ 157 | return *raiz; 158 | } 159 | if(info.valor > (*raiz)->info.valor ) 160 | return BuscaRecursiva( &((*raiz)->dir), info); 161 | else 162 | return BuscaRecursiva( &((*raiz)->esq), info); 163 | 164 | } 165 | 166 | 167 | -------------------------------------------------------------------------------- /C/Data_structures/linkedlist.c: -------------------------------------------------------------------------------- 1 | /* 2 | *creating a linked list 3 | * 4 | */ 5 | 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | 12 | typedef struct node 13 | { 14 | int pid; 15 | struct node* next; 16 | }node; 17 | 18 | void createlinkedlist(int n); 19 | node* head = NULL; 20 | int main() 21 | { 22 | createlinkedlist(5); 23 | return 0; 24 | } 25 | 26 | void createlinkedlist(int n) 27 | { 28 | int i; 29 | for(i = 0; i < n; i++) 30 | { 31 | node* newnode = malloc(sizeof(node)); 32 | if(head == NULL) 33 | { 34 | 35 | newnode->pid = i; 36 | newnode->next = NULL; 37 | head = newnode; 38 | } 39 | else 40 | { 41 | node* temp = head; 42 | node* curr = head; 43 | while(temp != NULL) 44 | { 45 | curr = temp; 46 | temp = temp->next; 47 | } 48 | curr->next = newnode; 49 | newnode->pid = i; 50 | newnode->next = NULL; 51 | } 52 | 53 | } 54 | printf("pid\n"); 55 | node* temp = head; 56 | while(temp != NULL) 57 | { 58 | printf("%d\n",temp->pid); 59 | temp = temp->next; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /C/Search/binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | #define Maxtam 20 4 | 5 | typedef struct Obj{ 6 | int key; // ordered by key 7 | int num; 8 | }Obj; 9 | /* 10 | returns the array indice 11 | key must be ordered 12 | */ 13 | int BinSearch(Obj vec[], int key){ 14 | int end=Maxtam-1,begin = 0, mid = (Maxtam-1)/2; 15 | while(begin vec[mid].key) 17 | begin = mid+1; 18 | else 19 | end = mid-1; 20 | 21 | mid = (begin+end)/2; 22 | } 23 | if(key == vec[mid].key) 24 | return mid; 25 | 26 | return -1; 27 | } 28 | 29 | main(){ 30 | Obj vec[Maxtam]; 31 | Obj aux; 32 | int x,key,indice; 33 | for(x=0; x0) 42 | printf("key - %d Value %d", vec[indice].key,vec[indice].num); 43 | 44 | else 45 | printf("Not Found"); 46 | 47 | } 48 | -------------------------------------------------------------------------------- /C/Sorting_algorithms/bubble_sort.c: -------------------------------------------------------------------------------- 1 | /* bubble_sort implementation in C - github.com/jfstn */ 2 | #include 3 | #include 4 | 5 | //void bubble_sort(int[], int); 6 | 7 | int main(){ 8 | int size; 9 | 10 | printf("Bubble Sort - C\n"); 11 | printf("Enter the number of elements:\n"); 12 | scanf("%d", &size); 13 | 14 | // array inicialization with random numbers 15 | int array[size], i; 16 | 17 | printf("Your random elements:\n"); 18 | for (i = 0; i < size; i++){ 19 | array[i] = rand() % 1000; 20 | printf("> %d <", array[i]); 21 | } 22 | 23 | // bubble sort 24 | int j, swap; 25 | 26 | for (i = 0; i < size; i++){ 27 | for (j = 0; j < size - i; j++){ 28 | if (array[j] > array[j + 1]){ 29 | swap = array[j]; 30 | array[j] = array[j + 1]; 31 | array[j + 1] = swap; 32 | } 33 | } 34 | } 35 | 36 | printf("\nSorted elements:\n"); 37 | for (i = 0; i < size; i++){ 38 | printf("> %d <", array[i]); 39 | } 40 | } -------------------------------------------------------------------------------- /C/Sorting_algorithms/heapsort.c: -------------------------------------------------------------------------------- 1 | 2 | // 3 | // Created by djsdvg on 26/10/17. 4 | // 5 | #define ARRAY_SIZE 100 6 | #include 7 | #include 8 | 9 | void heapify (int array[],int length, int i); 10 | void build_heap(int array[],int length); 11 | void heap_sort(int array[],int length); 12 | 13 | int main(int argc, const char * argv[]) { 14 | 15 | int array[ARRAY_SIZE]; 16 | int i; 17 | for(i=1;iarray[i]) 35 | largest=l; 36 | else 37 | largest=i; 38 | 39 | if(r<=length && array[r]>array[largest]) 40 | largest=r; 41 | if (largest!=i){ 42 | int temp=array[i]; 43 | array[i]=array[largest]; 44 | array[largest]=temp; 45 | heapify(array, length, largest); 46 | } 47 | } 48 | 49 | void build_heap(int array[],int length){ 50 | int i; 51 | for(i=length/2;i>0;i=i-1) 52 | heapify(array, length,i); 53 | } 54 | 55 | void heap_sort(int array[],int length){ 56 | build_heap(array, length); 57 | int i; 58 | for(i=length;i>1;i=i-1){ 59 | int temp=array[i]; 60 | array[i]=array[1]; 61 | array[1]=temp; 62 | length--; 63 | heapify(array, length,1); 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /C/Sorting_algorithms/insertion_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int i, j, num, temp, arr[1000]; 5 | 6 | printf("Enter total elements: "); 7 | scanf("%d", &num); 8 | 9 | printf("Enter %d elements: ", num); 10 | for (i = 0; i < num; i++) { 11 | scanf("%d", &arr[i]); 12 | } 13 | 14 | for (i = 1; i < num; i++) { 15 | temp = arr[i]; 16 | j = i - 1; 17 | while ((temp < arr[j]) && (j >= 0)) { 18 | arr[j + 1] = arr[j]; 19 | j = j - 1; 20 | } 21 | arr[j + 1] = temp; 22 | } 23 | 24 | printf("After Sorting: "); 25 | for (i = 0; i < num; i++) { 26 | printf("%d ", arr[i]); 27 | } 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /C/Sorting_algorithms/merge_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void Merge(int a[], int tmp[], int lpos, int rpos, int rend) 5 | { 6 | int i, lend, n, tmppos; 7 | lend = rpos - 1; 8 | tmppos = lpos; 9 | n = rend - lpos + 1; 10 | 11 | while(lpos <= lend && rpos <= rend) 12 | { 13 | if(a[lpos] <= a[rpos]) 14 | tmp[tmppos++] = a[lpos++]; 15 | else 16 | tmp[tmppos++] = a[rpos++]; 17 | } 18 | 19 | while(lpos <= lend) 20 | tmp[tmppos++] = a[lpos++]; 21 | while(rpos <= rend) 22 | tmp[tmppos++] = a[rpos++]; 23 | 24 | for(i = 0; i < n; i++, rend--) 25 | a[rend] = tmp[rend]; 26 | } 27 | 28 | void MSort(int a[], int tmp[], int left, int right) 29 | { 30 | int center; 31 | if(left < right) 32 | { 33 | center = (left + right) / 2; 34 | MSort(a, tmp, left, center); 35 | MSort(a, tmp, center + 1, right); 36 | Merge(a, tmp, left, center + 1, right); 37 | } 38 | } 39 | void MergeSort(int a[], int n) 40 | { 41 | int *tmparray; 42 | tmparray = malloc(sizeof(int) * n); 43 | MSort(a, tmparray, 0, n-1); 44 | free(tmparray); 45 | } 46 | main() 47 | { 48 | int i, n, a[10]; 49 | printf("Enter the number of elements :: "); 50 | scanf("%d",&n); 51 | printf("Enter the elements :: "); 52 | for(i = 0; i < n; i++) 53 | { 54 | scanf("%d",&a[i]); 55 | } 56 | MergeSort(a,n); 57 | printf("The sorted elements are :: "); 58 | for(i = 0; i < n; i++) 59 | printf("%d ",a[i]); 60 | printf("\n"); 61 | } -------------------------------------------------------------------------------- /C/Sorting_algorithms/quick_sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | //quick Sort function to Sort Integer array list 5 | void quicksort(int array[], int firstIndex, int lastIndex) 6 | { 7 | //declaring index variables 8 | int pivotIndex, temp, index1, index2; 9 | 10 | if(firstIndex < lastIndex) 11 | { 12 | //assigning first element index as pivot element 13 | pivotIndex = firstIndex; 14 | index1 = firstIndex; 15 | index2 = lastIndex; 16 | 17 | //Sorting in Ascending order with quick sort 18 | while(index1 < index2) 19 | { 20 | while(array[index1] <= array[pivotIndex] && index1 < lastIndex) 21 | { 22 | index1++; 23 | } 24 | while(array[index2]>array[pivotIndex]) 25 | { 26 | index2--; 27 | } 28 | 29 | if(index1 5 | #include 6 | #define SIZEARRAY 1000 //size of array 7 | int main (void){ 8 | 9 | int array[SIZEARRAY];//declaration of array 10 | int j,i,posmin; 11 | for(j=0;j 2 | 3 | int getMax(int arr[], int n) { 4 | int mx = arr[0]; 5 | int i; 6 | for (i = 1; i < n; i++) 7 | if (arr[i] > mx) 8 | mx = arr[i]; 9 | return mx; 10 | } 11 | 12 | void countSort(int arr[], int n, int exp) { 13 | int output[n]; // output array 14 | int i, count[10] = { 0 }; 15 | 16 | // Store count of occurrences in count[] 17 | for (i = 0; i < n; i++) 18 | count[(arr[i] / exp) % 10]++; 19 | 20 | for (i = 1; i < 10; i++) 21 | count[i] += count[i - 1]; 22 | 23 | // Build the output array 24 | for (i = n - 1; i >= 0; i--) { 25 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 26 | count[(arr[i] / exp) % 10]--; 27 | } 28 | 29 | for (i = 0; i < n; i++) 30 | arr[i] = output[i]; 31 | } 32 | 33 | // The main function to that sorts arr[] of size n using Radix Sort 34 | void radixsort(int arr[], int n) { 35 | int m = getMax(arr, n); 36 | 37 | int exp; 38 | for (exp = 1; m / exp > 0; exp *= 10) 39 | countSort(arr, n, exp); 40 | } 41 | 42 | void print(int arr[], int n) { 43 | int i; 44 | for (i = 0; i < n; i++) 45 | printf("%d ", arr[i]); 46 | } 47 | 48 | int main() { 49 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 50 | int n = sizeof(arr) / sizeof(arr[0]); 51 | radixsort(arr, n); 52 | print(arr, n); 53 | return 0; 54 | } 55 | -------------------------------------------------------------------------------- /R/Search/linear_search.R: -------------------------------------------------------------------------------- 1 | # Linear Search in R 2 | 3 | linear_search <- function(vec, num){ 4 | for (i in vec){ 5 | if (i == num) 6 | return(TRUE) 7 | } 8 | return(FALSE) 9 | } 10 | 11 | ans = linear_search( c(1:10), 7 ) 12 | 13 | ifelse(ans == TRUE, "Number found in vector", "Number not found in vector") -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms and Data Structures 2 | For Hacktoberfest 2017!
3 | Check your own profile stats after registering here: https://hacktoberfest.digitalocean.com/stats/ 4 | 5 | ### About 6 | This Repo consists of data-structures and algorithms sorted by programming language. 7 | 8 | ### Contributing Guidelines 9 | - The repository is structured language-wise i.e. algorithms in a certain language go in a specific folder. 10 | - The naming convention to be followed is ```algo_name.language_extention``` i.e. the overall pathshould be ```language/algo_name.language_extention``` 11 | - It is your choice to include only the function or the entire program for the algo. 12 | - If folder for your language does not exist, create a new one. 13 | - Don't be afraid to make a PR! 14 | 15 | ### How to make PR 16 | 1. Fork Repo on Web Page. 17 | 2. Make your changes on your forked repo. 18 | 3. Make Pull Request to master. 19 | 20 | Hack on! 21 | -------------------------------------------------------------------------------- /Rust/Sorts/bubblesort.rs: -------------------------------------------------------------------------------- 1 | fn bubblesort(array: &mut [i32]) { 2 | let mut n = array.len(); 3 | while n > 0 { 4 | let mut newn = 0; 5 | for i in 0..n-1 { 6 | if array[i] > array[i+1] { 7 | let temp = array[i]; 8 | array[i] = array[i+1]; 9 | array[i+1] = temp; 10 | newn = i+1; 11 | } 12 | } 13 | n = newn; 14 | } 15 | } 16 | 17 | fn main() { 18 | let mut values = [5, 8, 4, 1, 7, 2, 3, 6]; 19 | println!("values: {:?}", values); 20 | bubblesort(&mut values); 21 | println!("sorted: {:?}", values); 22 | } 23 | -------------------------------------------------------------------------------- /Rust/Sorts/insertionsort.rs: -------------------------------------------------------------------------------- 1 | fn insertionsort(array: &mut [i32]) { 2 | let mut i = 1; 3 | while i < array.len() { 4 | let mut j = i; 5 | while j > 0 && array[j-1] > array[j] { 6 | array.swap(j, j-1); 7 | j -= 1; 8 | } 9 | i += 1; 10 | } 11 | } 12 | 13 | fn main() { 14 | let mut values = [2, 36, 457, 3, 276, 865835, 3, 727, 2, 1]; 15 | println!("values: {:?}", values); 16 | insertionsort(&mut values); 17 | println!("sorted: {:?}", values); 18 | } 19 | -------------------------------------------------------------------------------- /c#/Data_structures/Trie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class Trie 5 | { 6 | private class TrieNode 7 | { 8 | public TrieNode(char value, bool isWord) 9 | { 10 | this.Value = value; 11 | this.IsWord = isWord; 12 | this.Children = new Dictionary(); 13 | 14 | if (isWord) 15 | { 16 | this.Count = 1; 17 | } 18 | else 19 | { 20 | this.Count = 0; 21 | } 22 | } 23 | 24 | public TrieNode(char value) 25 | : this(value, false) 26 | { 27 | } 28 | 29 | public TrieNode(bool isWord) 30 | : this(' ', isWord) 31 | { 32 | } 33 | 34 | public char Value { get; private set; } 35 | 36 | public bool IsWord { get; private set; } 37 | 38 | public int Count { get; private set; } 39 | 40 | public Dictionary Children { get; set; } 41 | 42 | public void AddChild(char value, bool isWord) 43 | { 44 | if (this.Children.ContainsKey(value)) 45 | { 46 | if (isWord) 47 | { 48 | this.Children[value].IsWord = true; 49 | this.Children[value].Count++; 50 | } 51 | } 52 | else 53 | { 54 | this.Children.Add(value, new TrieNode(value, isWord)); 55 | } 56 | } 57 | } 58 | 59 | private const char RootSymbol = '\0'; 60 | private readonly char[] Separators = { ' ', ',', '!', '.', ',', '?', '-', '\r', '\n' }; 61 | 62 | private TrieNode root; 63 | 64 | public Trie() 65 | { 66 | this.root = new TrieNode(RootSymbol, false); 67 | } 68 | 69 | public void BuildTrie(string text) 70 | { 71 | var wordsInText = text.Split(Separators, StringSplitOptions.RemoveEmptyEntries); 72 | 73 | foreach (var word in wordsInText) 74 | { 75 | this.AddWord(word.ToLower()); 76 | } 77 | } 78 | 79 | public void AddWord(string word) 80 | { 81 | var currentNode = this.root; 82 | 83 | bool isWord = false; 84 | 85 | for (int i = 0; i < word.Length; i++) 86 | { 87 | if (i == word.Length - 1) 88 | { 89 | isWord = true; 90 | } 91 | 92 | currentNode.AddChild(word[i], isWord); 93 | 94 | currentNode = currentNode.Children[word[i]]; 95 | } 96 | } 97 | 98 | public int GetWordOccurences(string word) 99 | { 100 | var currentNode = this.root; 101 | string wordToLower = word.ToLower(); 102 | 103 | for (int i = 0; i < wordToLower.Length; i++) 104 | { 105 | if (!currentNode.Children.ContainsKey(wordToLower[i])) 106 | { 107 | return -1; 108 | } 109 | 110 | currentNode = currentNode.Children[wordToLower[i]]; 111 | 112 | if (i == wordToLower.Length - 1 && currentNode.IsWord) 113 | { 114 | return currentNode.Count; 115 | } 116 | } 117 | 118 | return -1; 119 | } 120 | 121 | public bool ContainsWord(string word) 122 | { 123 | if (this.GetWordOccurences(word) == -1) 124 | { 125 | return false; 126 | } 127 | 128 | return true; 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /c#/Sorting_algorithms/merge_sort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Algorithms 4 | { 5 | public class MergeSort 6 | { 7 | public int[] Sort(int[] array) 8 | { 9 | if (array.Length <= 1) 10 | { 11 | return array; 12 | } 13 | 14 | var middle = array.Length / 2; 15 | 16 | var left = new int[middle]; 17 | var right = new int[array.Length - middle]; 18 | 19 | Array.Copy(array, left, middle); 20 | Array.Copy(array, middle, right, 0, right.Length); 21 | 22 | left = Sort(left); 23 | right = Sort(right); 24 | 25 | return Merge(left, right); 26 | } 27 | 28 | public int[] Merge(int[] left, int[] right) 29 | { 30 | var merged = new int[left.Length + right.Length]; 31 | 32 | var i = 0; 33 | var j = 0; 34 | 35 | for (var k = 0; k < merged.Length; k++) 36 | { 37 | if (left[i] < right[j]) 38 | { 39 | merged[k] = left[i++]; 40 | } 41 | else 42 | { 43 | if (right[j] < left[i]) 44 | { 45 | merged[k] = right[j++]; 46 | } 47 | } 48 | 49 | if (j >= right.Length) 50 | { 51 | return copy(left, i, merged, ++k); 52 | } 53 | 54 | if (i >= left.Length) 55 | { 56 | return copy(right, j, merged, ++k); 57 | } 58 | } 59 | 60 | return merged; 61 | } 62 | 63 | private int[] copy(int[] source, int sourceIndex, int[] destination, int destinationIndex) 64 | { 65 | var index = destinationIndex; 66 | 67 | for (var i = sourceIndex; i < source.Length; i++) 68 | { 69 | destination[index++] = source[i]; 70 | } 71 | 72 | return destination; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /clojure/README.md: -------------------------------------------------------------------------------- 1 | ### List of algorithms (Clojure) 2 | 3 | #### Search 4 | 5 | * Binary Search (`binary_chop.clj`) 6 | 7 | -------------------------------------------------------------------------------- /clojure/Search/binary_chop.clj: -------------------------------------------------------------------------------- 1 | (declare binary-chop index-at-half finished? found? too-small?) 2 | 3 | (def NOT_FOUND -1) 4 | 5 | (defn binary-search 6 | "Tries to find the needle in the haystack. Returns the 7 | index of the sought-after element in the haystack, 8 | otherwise -1." 9 | [needle haystack] 10 | (if (empty? haystack) 11 | NOT_FOUND 12 | (binary-chop needle haystack 0 (- (count haystack) 1)))) 13 | 14 | (defn- binary-chop [needle haystack lower-index upper-index] 15 | (let [mid-index (index-at-half lower-index upper-index) 16 | element (nth haystack mid-index)] 17 | (letfn [(finished? [] (> lower-index upper-index)) 18 | (found? [] (= element needle)) 19 | (too-small? [] (< element needle)) 20 | (search-lower [] (binary-chop needle haystack lower-index (- mid-index 1))) 21 | (search-upper [] (binary-chop needle haystack (+ mid-index 1) upper-index))] 22 | (cond 23 | (finished?) NOT_FOUND 24 | (found?) mid-index 25 | (too-small?) (search-upper) 26 | :else (search-lower))))) 27 | 28 | (defn- index-at-half [lower-index upper-index] 29 | (quot (+ lower-index upper-index) 2)) 30 | -------------------------------------------------------------------------------- /cpp/BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | //NODE 6 | struct node 7 | { 8 | int data; 9 | node *left; 10 | node *right; 11 | node *parent; 12 | }; 13 | 14 | 15 | node *root=NULL, *ptr; 16 | 17 | //INSERT 18 | node* insert(node *root, int key){ 19 | 20 | if(root==NULL){ 21 | ptr = new node; 22 | ptr->data = key; 23 | ptr->left=NULL; 24 | ptr->right=NULL; 25 | ptr->parent=NULL; 26 | root= ptr; 27 | return root; 28 | } 29 | else if(key<=root->data){ 30 | root->left = insert(root->left, key); 31 | root->parent = root; 32 | }else if(key>root->data){ 33 | root->right = insert(root->right, key); 34 | root->parent=root; 35 | } 36 | return root; 37 | } 38 | 39 | //INORDER TRAERSAL 40 | void inorder(node *root){ 41 | 42 | if(root==NULL){ 43 | return; 44 | } 45 | inorder(root->left); 46 | cout<data<<" "; 47 | inorder(root->right); 48 | } 49 | 50 | //PRE ORDER TRAVERSAL 51 | void preorder(node *root){ 52 | 53 | if(root==NULL){ 54 | return; 55 | } 56 | cout<data<<" "; 57 | inorder(root->left); 58 | inorder(root->right); 59 | } 60 | 61 | //POST ORDER TRAVERSAL 62 | void postorder(node *root){ 63 | 64 | if(root==NULL){ 65 | return; 66 | } 67 | inorder(root->left); 68 | inorder(root->right); 69 | cout<data<<" "; 70 | } 71 | 72 | //SEARCH 73 | node* search(node *root, int key){ 74 | 75 | if(root==NULL){ 76 | return root; 77 | } 78 | if(root->data==key){ 79 | return root; 80 | } 81 | return search(root->left, key); 82 | return search(root->right, key); 83 | } 84 | 85 | //FIND MIN NODE 86 | node* FindMin(node* root){ 87 | if(root==NULL){ 88 | return root; 89 | } 90 | if(root->left==NULL){ 91 | return root; 92 | } 93 | return FindMin(root->left); 94 | } 95 | 96 | //FINDMAX NODE 97 | node* FindMax(node* root){ 98 | if(root==NULL){ 99 | return root; 100 | } 101 | if(root->right==NULL){ 102 | return root; 103 | } 104 | return FindMin(root->right); 105 | } 106 | 107 | //DELETE A NODE 108 | node* dele(node *root, int key){ 109 | if(root==NULL){ 110 | return root; 111 | } 112 | else if(keydata){ 113 | root->left = dele(root->left, key); 114 | }else if (key>root->data){ 115 | root->right = dele(root->right, key); 116 | }else{ 117 | 118 | //NO CHILD 119 | if(root->left==NULL && root->right==NULL){ 120 | delete root; 121 | root=NULL; 122 | } 123 | 124 | //ONE CHILD 125 | else if(root->left==NULL){ 126 | node *temp = root; 127 | root=root->right; 128 | delete temp; 129 | } 130 | else if(root->right==NULL){ 131 | node *temp = root; 132 | root=root->left; 133 | delete temp; 134 | } 135 | 136 | //TWO CHILD 137 | else{ 138 | node *temp = FindMin(root->right); 139 | root->data = temp->data; 140 | root->right= dele(root->right, temp->data); 141 | } 142 | } 143 | 144 | return root; 145 | } 146 | 147 | 148 | 149 | int main(){ 150 | 151 | //CREATE A TREE 152 | 153 | root = insert(root,50); 154 | 155 | insert(root,23); 156 | 157 | insert(root,18); 158 | 159 | insert(root,25); 160 | 161 | insert(root, 60); 162 | 163 | insert(root, 67); 164 | 165 | //INORDER TRAVERSE 166 | 167 | inorder(root); 168 | 169 | //SEARCH FOR A DATA 170 | 171 | cout<<"\n\n"<data; 172 | 173 | //DELETE A DATA 174 | dele(root, 23); 175 | 176 | cout<<"\n\n"; 177 | 178 | inorder(root); 179 | 180 | return 0; 181 | } 182 | -------------------------------------------------------------------------------- /cpp/Data_structures/Dial_algorithm.cpp: -------------------------------------------------------------------------------- 1 | // C++ Program for Dijkstra's dial implementation 2 | #include 3 | using namespace std; 4 | # define INF 0x3f3f3f3f 5 | 6 | // This class represents a directed graph using 7 | // adjacency list representation 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | 12 | // In a weighted graph, we need to store vertex 13 | // and weight pair for every edge 14 | list< pair > *adj; 15 | 16 | public: 17 | Graph(int V); // Constructor 18 | 19 | // function to add an edge to graph 20 | void addEdge(int u, int v, int w); 21 | 22 | // prints shortest path from s 23 | void shortestPath(int s, int W); 24 | }; 25 | 26 | // Allocates memory for adjacency list 27 | Graph::Graph(int V) 28 | { 29 | this->V = V; 30 | adj = new list< pair >[V]; 31 | } 32 | 33 | // adds edge between u and v of weight w 34 | void Graph::addEdge(int u, int v, int w) 35 | { 36 | adj[u].push_back(make_pair(v, w)); 37 | adj[v].push_back(make_pair(u, w)); 38 | } 39 | 40 | // Prints shortest paths from src to all other vertices. 41 | // W is the maximum weight of an edge 42 | void Graph::shortestPath(int src, int W) 43 | { 44 | /* With each distance, iterator to that vertex in 45 | its bucket is stored so that vertex can be deleted 46 | in O(1) at time of updation. So 47 | dist[i].first = distance of ith vertex from src vertex 48 | dits[i].second = iterator to vertex i in bucket number */ 49 | vector::iterator> > dist(V); 50 | 51 | // Initialize all distances as infinite (INF) 52 | for (int i = 0; i < V; i++) 53 | dist[i].first = INF; 54 | 55 | // Create buckets B[]. 56 | // B[i] keep vertex of distance label i 57 | list B[W * V + 1]; 58 | 59 | B[0].push_back(src); 60 | dist[src].first = 0; 61 | 62 | // 63 | int idx = 0; 64 | while (1) 65 | { 66 | // Go sequentially through buckets till one non-empty 67 | // bucket is found 68 | while (B[idx].size() == 0 && idx < W*V) 69 | idx++; 70 | 71 | // If all buckets are empty, we are done. 72 | if (idx == W * V) 73 | break; 74 | 75 | // Take top vertex from bucket and pop it 76 | int u = B[idx].front(); 77 | B[idx].pop_front(); 78 | 79 | // Process all adjacents of extracted vertex 'u' and 80 | // update their distanced if required. 81 | for (auto i = adj[u].begin(); i != adj[u].end(); ++i) 82 | { 83 | int v = (*i).first; 84 | int weight = (*i).second; 85 | 86 | int du = dist[u].first; 87 | int dv = dist[v].first; 88 | 89 | // If there is shorted path to v through u. 90 | if (dv > du + weight) 91 | { 92 | // If dv is not INF then it must be in B[dv] 93 | // bucket, so erase its entry using iterator 94 | // in O(1) 95 | if (dv != INF) 96 | B[dv].erase(dist[v].second); 97 | 98 | // updating the distance 99 | dist[v].first = du + weight; 100 | dv = dist[v].first; 101 | 102 | // pushing vertex v into updated distance's bucket 103 | B[dv].push_front(v); 104 | 105 | // storing updated iterator in dist[v].second 106 | dist[v].second = B[dv].begin(); 107 | } 108 | } 109 | } 110 | 111 | // Print shortest distances stored in dist[] 112 | printf("Vertex Distance from Source\n"); 113 | for (int i = 0; i < V; ++i) 114 | printf("%d %d\n", i, dist[i].first); 115 | } 116 | 117 | // Driver program to test methods of graph class 118 | int main() 119 | { 120 | // create the graph given in above fugure 121 | int V = 9; 122 | Graph g(V); 123 | 124 | // making above shown graph 125 | g.addEdge(0, 1, 4); 126 | g.addEdge(0, 7, 8); 127 | g.addEdge(1, 2, 8); 128 | g.addEdge(1, 7, 11); 129 | g.addEdge(2, 3, 7); 130 | g.addEdge(2, 8, 2); 131 | g.addEdge(2, 5, 4); 132 | g.addEdge(3, 4, 9); 133 | g.addEdge(3, 5, 14); 134 | g.addEdge(4, 5, 10); 135 | g.addEdge(5, 6, 2); 136 | g.addEdge(6, 7, 1); 137 | g.addEdge(6, 8, 6); 138 | g.addEdge(7, 8, 7); 139 | 140 | // maximum weighted edge - 14 141 | g.shortestPath(0, 14); 142 | 143 | return 0; 144 | } 145 | -------------------------------------------------------------------------------- /cpp/Data_structures/Stack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | template 5 | struct Item 6 | { 7 | public: 8 | T value; 9 | Item *next; 10 | }; 11 | 12 | template 13 | class Stack 14 | { 15 | private: 16 | Item *items = nullptr; 17 | public: 18 | void push(const T &item) 19 | { 20 | auto itm = new Item(); 21 | itm->value = item; 22 | itm->next = items; 23 | items = itm; 24 | } 25 | 26 | T pop() 27 | { 28 | if(this->items != nullptr) 29 | { 30 | T value; 31 | auto item = this->items; 32 | value = item->value; 33 | this->items = item->next; 34 | delete item; 35 | return value; 36 | } 37 | throw std::out_of_range("Empty stack"); 38 | } 39 | 40 | bool isEmpty() 41 | { 42 | return this->items == nullptr; 43 | } 44 | }; 45 | 46 | int main() 47 | { 48 | Stack stack; 49 | stack.push(223); 50 | stack.push(15); 51 | stack.push(3); 52 | stack.push(2); 53 | stack.push(1); 54 | 55 | while(!stack.isEmpty()) 56 | std::cout< strStack; 59 | strStack.push("world!"); 60 | strStack.push("Hello "); 61 | 62 | std::cout< 5 | #include 6 | 7 | using namespace std; 8 | 9 | #define MAX 120 10 | #define INF 500000000 11 | 12 | int adjacency_matrix[MAX][MAX]; 13 | 14 | int main(){ 15 | 16 | int number_of_nodes; 17 | 18 | scanf("%d",&number_of_nodes); 19 | 20 | // Initialize all distances as infinity. 21 | for(int i = 0;i <= number_of_nodes;++i){ 22 | for(int j = 0;j <= number_of_nodes;++j){ 23 | adjacency_matrix[i][j] = INF; 24 | } 25 | } 26 | 27 | int origin,destiny; 28 | int number_of_edges,cost; 29 | 30 | scanf("%d",&number_of_edges); 31 | // Store costs between neighbor nodes. 32 | for(int i = 0;i < number_of_edges;++i){ 33 | scanf("%d %d %d",&origin,&destiny,&cost); 34 | adjacency_matrix[origin][destiny] = cost; 35 | adjacency_matrix[destiny][origin] = cost; 36 | } 37 | 38 | for(int k =0;k < number_of_nodes;++k) 39 | for(int i =0;i 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Number of vertices in the graph 7 | #define N 15 8 | 9 | // data structure to store graph edges 10 | struct Edge { 11 | int src, dest; 12 | }; 13 | 14 | // class to represent a graph object 15 | class Graph 16 | { 17 | public: 18 | // A array of vectors to represent adjacency list 19 | vector adjList[N]; 20 | 21 | // Constructor 22 | Graph(vector edges) 23 | { 24 | // add edges to the undirected graph 25 | for (unsigned i = 0; i < edges.size(); i++) 26 | { 27 | int src = edges[i].src; 28 | int dest = edges[i].dest; 29 | 30 | adjList[src].push_back(dest); 31 | adjList[dest].push_back(src); 32 | } 33 | } 34 | }; 35 | 36 | // Perform BFS on graph starting from vertex v 37 | int BFS(Graph const &graph, int v, vector &discovered) 38 | { 39 | // create a queue used to do BFS 40 | queue q; 41 | 42 | // mark source vertex as discovered 43 | discovered[v] = true; 44 | 45 | // push source vertex into the queue 46 | q.push(v); 47 | 48 | // run till queue is not empty 49 | while (!q.empty()) 50 | { 51 | // pop front node from queue and print it 52 | v = q.front(); 53 | q.pop(); 54 | cout << v << " "; 55 | 56 | // do for every edge (v -> u) 57 | for (int u : graph.adjList[v]) 58 | if (!discovered[u]) 59 | { 60 | // mark it discovered and push it into queue 61 | discovered[u] = true; 62 | q.push(u); 63 | } 64 | } 65 | } 66 | 67 | // Iterative C++ implementation of Breadth first search 68 | int main() 69 | { 70 | // vector of graph edges as per above diagram 71 | vector edges = { 72 | {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {5, 9}, 73 | {5, 10}, {4, 7}, {4, 8}, {7, 11}, {7, 12} 74 | // vertex 0, 13 and 14 are single nodes 75 | }; 76 | 77 | // create a graph from edges 78 | Graph graph(edges); 79 | 80 | // stores vertex is discovered or not 81 | vector discovered(N); 82 | 83 | // Do BFS traversal from all undiscovered nodes to 84 | // cover all unconnected components of graph 85 | for (int i = 0; i < N; i++) { 86 | if (discovered[i] == false) { 87 | // start BFS traversal from vertex i 88 | BFS(graph, i, discovered); 89 | } 90 | } 91 | 92 | return 0; 93 | } 94 | -------------------------------------------------------------------------------- /cpp/Data_structures/bfs_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // Number of vertices in the graph 7 | #define N 15 8 | 9 | // data structure to store graph edges 10 | struct Edge { 11 | int src, dest; 12 | }; 13 | 14 | // class to represent a graph object 15 | class Graph 16 | { 17 | public: 18 | // A array of vectors to represent adjacency list 19 | vector adjList[N]; 20 | 21 | // Constructor 22 | Graph(vector edges) 23 | { 24 | // add edges to the undirected graph 25 | for (unsigned i = 0; i < edges.size(); i++) 26 | { 27 | int src = edges[i].src; 28 | int dest = edges[i].dest; 29 | 30 | adjList[src].push_back(dest); 31 | adjList[dest].push_back(src); 32 | } 33 | } 34 | }; 35 | 36 | // Perform BFS recursively on graph 37 | void recursiveBFS(Graph const &graph, queue &q, 38 | vector &discovered) 39 | { 40 | if (q.empty()) 41 | return; 42 | 43 | // pop front node from queue and print it 44 | int v = q.front(); 45 | q.pop(); 46 | cout << v << " "; 47 | 48 | // do for every edge (v -> u) 49 | for (int u : graph.adjList[v]) 50 | { 51 | if (!discovered[u]) 52 | { 53 | // mark it discovered and push it into queue 54 | discovered[u] = true; 55 | q.push(u); 56 | } 57 | } 58 | 59 | recursiveBFS(graph, q, discovered); 60 | } 61 | 62 | // Recursive C++ implementation of Breadth first search 63 | int main() 64 | { 65 | // vector of graph edges as per above diagram 66 | vector edges = { 67 | {1, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {5, 9}, 68 | {5, 10}, {4, 7}, {4, 8}, {7, 11}, {7, 12} 69 | // vertex 0, 13 and 14 are single nodes 70 | }; 71 | 72 | // create a graph from edges 73 | Graph graph(edges); 74 | 75 | // stores vertex is discovered or not 76 | vector discovered(N); 77 | 78 | // create a queue used to do BFS 79 | queue q; 80 | 81 | // Do BFS traversal from all undiscovered nodes to 82 | // cover all unconnected components of graph 83 | for (int i = 0; i < N; i++) { 84 | if (discovered[i] == false) 85 | { 86 | // mark source vertex as discovered 87 | discovered[i] = true; 88 | 89 | // push source vertex into the queue 90 | q.push(i); 91 | 92 | // start BFS traversal from vertex i 93 | recursiveBFS(graph, q, discovered); 94 | } 95 | } 96 | 97 | return 0; 98 | } 99 | -------------------------------------------------------------------------------- /cpp/Data_structures/bicolorable_graph.cpp: -------------------------------------------------------------------------------- 1 | // Complexity: O(n^2) 2 | // Test if a given graph is a Bicolorable Graph. 3 | // A Bipartite Graph or Bicolorable Graph, is a graph whose vertices can be divided into two disjoint and independent sets U and V such that every edge connects a vertex in U to one in V. 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | #define MAX 210 12 | bool bicolorable = true; 13 | 14 | vector adjacency_list[MAX]; 15 | int colors[MAX]; 16 | 17 | // Try to assign colors to nodes, so that no node share the same color with its neighbor; 18 | void dfs(int node,int color){ 19 | 20 | if(not bicolorable) return; 21 | 22 | colors[node] = color; 23 | 24 | for (auto it : adjacency_list[node]) 25 | { 26 | if(colors[it] == -1){ 27 | dfs(it,1 - color); 28 | }else if(colors[it] == colors[node]){ 29 | bicolorable = false; 30 | break; 31 | } 32 | } 33 | 34 | } 35 | 36 | int main(){ 37 | 38 | // Initalize all colors position with -1 values. That means no node has been colored yet; 39 | memset(colors,-1,sizeof colors); 40 | 41 | int number_of_adjancencies; 42 | scanf("%d",&number_of_adjancencies); 43 | 44 | int origin,destiny; 45 | 46 | // Fill adjancencies between nodes 47 | for(int i = 0;i < number_of_adjancencies;++i){ 48 | scanf("%d %d",&origin,&destiny); 49 | adjacency_list[origin].push_back(destiny); 50 | adjacency_list[destiny].push_back(origin); 51 | } 52 | 53 | dfs(0,0); 54 | 55 | printf("%s\n",(bicolorable?"THIS GRAPH IS BICOLORABLE.":"THIS GRAPH IS NOT BICOLORABLE.")); 56 | 57 | return 0; 58 | 59 | } 60 | -------------------------------------------------------------------------------- /cpp/Data_structures/counting_inversion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | typedef long long ll; 5 | #define rep(i, n) for(int i = 0; i < n; ++i) 6 | #define test int t; cin >> t; while(t--) 7 | #define debug(x) cout << '>' << #x << ':' << x << "\n"; 8 | #define endl '\n' 9 | 10 | // Counter for inversions 11 | int total = 0; 12 | // Auxiliary array for merging 13 | int aux[1000]; 14 | 15 | // Function for Conquering 16 | void join(int* a, int low, int high) { 17 | int mid = (low + high) >> 1; 18 | int k = 0, i, j; 19 | 20 | for(i = low, j = mid + 1; i < mid + 1 && j < high + 1;) { 21 | if (a[i] > a[j]) { 22 | aux[k] = a[j]; 23 | j++; 24 | k++; 25 | total += mid - i + 1; 26 | } 27 | else { 28 | aux[k] = a[i]; 29 | i++; 30 | k++; 31 | } 32 | } 33 | 34 | while(i < mid+1) { 35 | aux[k] = a[i]; 36 | k++; 37 | i++; 38 | } 39 | while(j < high+1) { 40 | aux[k] = a[j]; 41 | j++; 42 | k++; 43 | } 44 | 45 | rep(z, k) { 46 | a[z+low] = aux[z]; 47 | } 48 | } 49 | 50 | // Function for Dividing 51 | void half(int* a, int low, int high) { 52 | if (high <= low) { 53 | return; 54 | } 55 | int mid = (low + high) >> 1; 56 | half(a, low, mid); 57 | half(a, mid+1, high); 58 | join(a, low, high); 59 | } 60 | 61 | int main() { 62 | int a[100007]; 63 | test { 64 | int n; 65 | cin >> n; 66 | rep(i, n) { 67 | cin >> a[i]; 68 | } 69 | 70 | half(a, 0, n-1); 71 | cout << total << endl; 72 | } 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /cpp/Data_structures/cpp-boilerplate.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main(){ 5 | //code 6 | 7 | return 0; 8 | } 9 | -------------------------------------------------------------------------------- /cpp/Data_structures/dfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Number of vertices in the graph 4 | #define N 13 5 | 6 | // data structure to store graph edges 7 | struct Edge { 8 | int src, dest; 9 | }; 10 | 11 | // class to represent a graph object 12 | class Graph 13 | { 14 | public: 15 | // A array of vectors to represent adjacency list 16 | vector adjList[N]; 17 | 18 | // Constructor 19 | Graph(vector edges) 20 | { 21 | // add edges to the undirected graph 22 | for (int i = 0; i < edges.size(); i++) 23 | { 24 | int src = edges[i].src; 25 | int dest = edges[i].dest; 26 | 27 | adjList[src].push_back(dest); 28 | adjList[dest].push_back(src); 29 | } 30 | } 31 | }; 32 | 33 | // Perform iterative DFS on graph g starting from vertex v 34 | int iterativeDFS(Graph const &graph, int v) 35 | { 36 | // stores vertex is discovered or not 37 | vector discovered(N); 38 | 39 | // create a stack used to do iterative DFS 40 | stack stack; 41 | 42 | // push the source node into stack 43 | stack.push(v); 44 | 45 | // run till stack is not empty 46 | while (!stack.empty()) 47 | { 48 | // Pop a vertex from stack 49 | v = stack.top(); 50 | stack.pop(); 51 | 52 | // if the vertex is already discovered yet, 53 | // ignore it 54 | if (discovered[v]) 55 | continue; 56 | 57 | // we will reach here if the popped vertex v 58 | // is not discovered yet. We print it and process 59 | // its undiscovered adjacent nodes into stack 60 | discovered[v] = true; 61 | cout << v << " "; 62 | 63 | // do for every edge (v -> u) 64 | // we use reverse iterator (Why?) 65 | for (auto it = graph.adjList[v].rbegin(); 66 | it != graph.adjList[v].rend(); ++it) 67 | { 68 | int u = *it; 69 | if (!discovered[u]) 70 | stack.push(u); 71 | } 72 | } 73 | } 74 | 75 | // main function 76 | int main() 77 | { 78 | // vector of graph edges as per above diagram 79 | vector edges = { 80 | {1, 2}, {1, 7}, {1, 8}, {2, 3}, {2, 6}, {3, 4}, 81 | {3, 5}, {8, 9}, {8, 12}, {9, 10}, {9, 11} 82 | // , {6, 9} // introduce cycle 83 | }; 84 | 85 | // create a graph from given edges 86 | Graph graph(edges); 87 | 88 | // Do iterative DFS traversal from vertex 1 89 | iterativeDFS(graph, 1); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /cpp/Data_structures/dfs_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // Number of vertices in the graph 4 | #define N 13 5 | 6 | // data structure to store graph edges 7 | struct Edge { 8 | int src, dest; 9 | }; 10 | 11 | // class to represent a graph object 12 | class Graph 13 | { 14 | public: 15 | // A array of vectors to represent adjacency list 16 | vector adjList[N]; 17 | 18 | // Constructor 19 | Graph(vector edges) 20 | { 21 | // add edges to the undirected graph 22 | for (int i = 0; i < edges.size(); i++) 23 | { 24 | int src = edges[i].src; 25 | int dest = edges[i].dest; 26 | 27 | adjList[src].push_back(dest); 28 | adjList[dest].push_back(src); 29 | } 30 | } 31 | }; 32 | 33 | // Function to perform DFS Traversal 34 | int DFS(Graph const &graph, int v, vector &discovered) 35 | { 36 | // mark current node as discovered 37 | discovered[v] = true; 38 | 39 | // print current node 40 | cout << v << " "; 41 | 42 | // do for every edge (v -> u) 43 | for (int u : graph.adjList[v]) 44 | { 45 | // u is not discovered 46 | if (!discovered[u]) 47 | DFS(graph, u, discovered); 48 | } 49 | } 50 | 51 | // main function 52 | int main() 53 | { 54 | // vector of graph edges as per above diagram 55 | vector edges = { 56 | {1, 2}, {1, 7}, {1, 8}, {2, 3}, {2, 6}, {3, 4}, 57 | {3, 5}, {8, 9}, {8, 12}, {9, 10}, {9, 11} 58 | }; 59 | 60 | // create a graph from given edges 61 | Graph graph(edges); 62 | 63 | // stores vertex is discovered or not 64 | vector discovered(N); 65 | 66 | // Do DFS traversal from all undiscovered nodes to 67 | // cover all unconnected components of graph 68 | for (int i = 1; i < N; i++) 69 | if (discovered[i] == false) 70 | DFS(graph, i, discovered); 71 | 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /cpp/Data_structures/heap.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | struct Heap{ 6 | int *arr; 7 | int size; 8 | 9 | Heap(int n){ 10 | this->size = 0; 11 | arr = new int[n+1]; 12 | } 13 | 14 | void insert(int x){ 15 | arr[++size] = x; 16 | heapify(arr,size); 17 | } 18 | 19 | void heapify(int arr[],int size){ 20 | if(size/2 < 1) return; 21 | int temp = size/2; 22 | int x = size; 23 | while(temp && arr[x]>arr[temp]){ 24 | int t = arr[temp]; 25 | arr[temp] = arr[x]; 26 | arr[x] = t; 27 | x = temp; 28 | temp /= 2; 29 | } 30 | } 31 | 32 | void heapifyDown(int arr[],int size){ 33 | int x = 1; 34 | int sw = 2 * x; 35 | while(sw <= size ){ 36 | if(sw+1 <= size && arr[sw+1] > arr[sw]){ 37 | sw++; 38 | } 39 | if(arr[sw] < arr[x]) 40 | break; 41 | int temp = arr[sw]; 42 | arr[sw] = arr[x]; 43 | arr[x] = temp; 44 | x = sw; 45 | sw = 2 * x; 46 | } 47 | } 48 | 49 | void print(){ 50 | cout<<"Heap is \n"; 51 | for(int i=1;i<=size;i++){ 52 | cout<>n; 81 | Heap heap(n); 82 | cout<<"Enter elems \n"; 83 | for(int i=0;i>x; 86 | heap.insert(x); 87 | } 88 | heap.print(); 89 | heap.heapsort(); 90 | } -------------------------------------------------------------------------------- /cpp/Data_structures/intersection.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node{ 4 | long long int data; 5 | struct node *next; 6 | }; 7 | 8 | node* create(int size){ 9 | struct node *start,*temp,*end,*p; 10 | p=new node; 11 | temp=start=p; 12 | long long int x; 13 | cin>>x; 14 | p->data=x; 15 | for(int i=1;inext=p; 18 | cin>>x; 19 | p->data=x; 20 | p->next= NULL; 21 | temp=p; 22 | } 23 | end=temp; 24 | return start; 25 | } 26 | void display(node *start){ 27 | node *p,*ptr; 28 | ptr=p=start; 29 | cout<data<<" "; 30 | while(ptr->next!=NULL){ 31 | ptr=ptr->next; 32 | cout<data<<" "; 33 | } 34 | } 35 | 36 | int inter(node *p,node *s,int n,int m){ 37 | int t=n+m; 38 | int flag=1; 39 | long long int x=-10000000001; 40 | while(t--){ 41 | if(p==NULL){ 42 | if(flag) 43 | cout<<"-1"; 44 | return -1; 45 | } 46 | else if(s==NULL){ 47 | if(flag) 48 | cout<<"-1 "; 49 | return -1; 50 | } 51 | else if(s->data==p->data){ 52 | if(x!=s->data){ 53 | cout<data<<" "; 54 | flag=0; 55 | x=s->data; 56 | } 57 | s=s->next; 58 | p=p->next; 59 | t--; 60 | } 61 | else if(s->datadata){ 62 | s=s->next; 63 | } 64 | else { 65 | p=p->next; 66 | } 67 | } 68 | return -1; 69 | } 70 | int main() 71 | { 72 | int n,m; 73 | node *p,*s; 74 | cin>>n; 75 | p=create(n); 76 | cin>>m; 77 | s=create(m); 78 | inter(p,s,n,m); 79 | return 0; 80 | } 81 | 82 | -------------------------------------------------------------------------------- /cpp/Data_structures/linear_search.cpp: -------------------------------------------------------------------------------- 1 | /** 2 | *linear search 3 | * 4 | * 5 | **/ 6 | 7 | 8 | #include 9 | #include 10 | 11 | using namespace std; 12 | 13 | int linear_search(int arr[], int ele); 14 | int main() 15 | { 16 | int arr[] = {2, 3, 4 ,6 ,7}; 17 | int ans = linear_search(arr, 7); 18 | if(ans == 0) 19 | cout<<"found!\n"; 20 | else 21 | cout<<"not found!\n"; 22 | return 0; 23 | } 24 | int linear_search(int arr[], int ele) 25 | { 26 | int i; 27 | int len = sizeof(arr); 28 | for(i = 0; i < len; i++) 29 | { 30 | if(arr[i] == ele) 31 | return 0; 32 | } 33 | return 1; 34 | } 35 | -------------------------------------------------------------------------------- /cpp/Data_structures/middle_element_in_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node{ 4 | long long int data; 5 | struct node *next; 6 | }; 7 | 8 | node* create(int size){ 9 | struct node *start,*temp,*end,*p; 10 | p=new node; 11 | temp=start=p; 12 | cin>>p->data; 13 | for(int i=1;inext=p; 16 | cin>>p->data; 17 | p->next= NULL; 18 | temp=p; 19 | } 20 | end=temp; 21 | return start; 22 | } 23 | node *midd(node *start){ 24 | node *ptr,*ptr2; 25 | ptr=ptr2=start; 26 | if(ptr2->next!=NULL)ptr2=ptr2->next; 27 | while(ptr2->next!=NULL){ 28 | ptr=ptr->next; 29 | ptr2=ptr2->next; 30 | if(ptr2->next!=NULL)ptr2=ptr2->next; 31 | } 32 | return ptr; 33 | } 34 | void display(node *start){ 35 | node *p,*ptr; 36 | ptr=p=start; 37 | cout<data<<" "; 38 | while(ptr->next!=NULL){ 39 | ptr=ptr->next; 40 | cout<data<<" "; 41 | } 42 | } 43 | int main() 44 | { 45 | node *p,*x; 46 | long long int t; 47 | cin>>t; 48 | p=create(t); 49 | x=midd(p); 50 | cout<data; 51 | return 0; 52 | } 53 | 54 | 55 | -------------------------------------------------------------------------------- /cpp/Data_structures/modular_inverse.cpp: -------------------------------------------------------------------------------- 1 | // Complexity: O(log(n)) 2 | // Computes the modular inverse of n modulo P 3 | 4 | #include 5 | 6 | using namespace std; 7 | using ull = unsigned long long; 8 | 9 | ull P; 10 | 11 | // Fast Exponentiation technique calculates n^factor with O(log(n)) complexity. 12 | ull fast_exponentiation(ull n,ull factor){ 13 | ull x; 14 | 15 | if(factor==0) return 1; 16 | if(factor==1) return n; 17 | 18 | if(factor%2==0){ 19 | x = fast_exponentiation(n,factor/2)%P; 20 | return (x*x)%P; 21 | }else{ 22 | return (n*fast_exponentiation(n,factor-1))%P; 23 | } 24 | } 25 | 26 | // Fermat's little theorem => a^(p-1)= 1 mod p 27 | // therefore => a*a^(p-2)=1 mod p => inv(a) = a(p-2) mod p 28 | ull modular_inverse(ull n){ 29 | return fast_exponentiation(n,P-2); 30 | } 31 | 32 | int main(){ 33 | ull n; 34 | cin >> n >> P; 35 | 36 | cout << modular_inverse(n) << endl; 37 | 38 | return 0; 39 | } 40 | -------------------------------------------------------------------------------- /cpp/Data_structures/reverse_a_linkedlist.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node{ 4 | long long int data; 5 | struct node *next; 6 | }; 7 | 8 | node* create(int size){ 9 | struct node *start,*temp,*end,*p; 10 | p=new node; 11 | temp=start=p; 12 | cin>>p->data; 13 | for(int i=1;inext=p; 16 | cin>>p->data; 17 | p->next= NULL; 18 | temp=p; 19 | } 20 | end=temp; 21 | return start; 22 | } 23 | node* rev(node *start){ 24 | node *temp,*ptr,*p; 25 | p=start; 26 | temp=ptr=NULL; 27 | while(p!=NULL){ 28 | temp=p->next; 29 | p->next=ptr; 30 | ptr=p; 31 | p=temp; 32 | } 33 | return ptr; 34 | } 35 | void display(node *start){ 36 | node *p,*ptr; 37 | ptr=p=start; 38 | cout<data<<" "; 39 | while(ptr->next!=NULL){ 40 | ptr=ptr->next; 41 | cout<data<<" "; 42 | } 43 | } 44 | int main() 45 | { 46 | node *p; 47 | long long int t; 48 | cin>>t; 49 | p=create(t); 50 | p=rev(p); 51 | display(p); 52 | return 0; 53 | } 54 | 55 | -------------------------------------------------------------------------------- /cpp/InterpolationSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int InterpolationSearch(int A[],int size,int data){ 4 | int low=0,mid,high=size-1; 5 | while(low<=high){ 6 | mid=low+(((data-A[low])*(high-low))/(A[high]-A[low])); 7 | if(data==A[mid]) 8 | return mid+1; 9 | if(data 2 | #include 3 | 4 | // A recursive binary search algorithm. 5 | // It returns location of x in a given array arr[l..r] is present, otherwise -1 6 | int binarySearch(int arr[], int l, int r, int x) 7 | { 8 | if (r >= l) 9 | { 10 | int mid = l + (r - l) / 2; 11 | 12 | // If the element is present at the middle itself 13 | if (arr[mid] == x) return mid; 14 | 15 | // If element is smaller than mid, then it can only be present 16 | // in left subarray 17 | if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); 18 | 19 | // Else the element can only be present in right subarray 20 | return binarySearch(arr, mid + 1, r, x); 21 | } 22 | 23 | // We reach here when element is not present in array 24 | return -1; 25 | } 26 | 27 | 28 | int search(int* arr, int x){ 29 | int n = sizeof(arr) / sizeof(arr[0]); 30 | return binarySearch(arr, 0, n, x); 31 | } 32 | 33 | 34 | int main(void) 35 | { 36 | int arr[] = {2, 3, 4, 10, 40}; 37 | int x = 3; 38 | int result = search(arr, x); 39 | (result == -1) ? printf("Element is not present in array") 40 | : printf("Element is present at index %d \n", result); 41 | system("pause"); 42 | return 0; 43 | } -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/HeapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void heapify(int arr[], int n, int i) 5 | { 6 | int largest = i; // Initialize largest as root 7 | int l = 2*i + 1; // left = 2*i + 1 8 | int r = 2*i + 2; // right = 2*i + 2 9 | 10 | if (l < n && arr[l] > arr[largest]) 11 | largest = l; 12 | 13 | 14 | if (r < n && arr[r] > arr[largest]) 15 | largest = r; 16 | 17 | if (largest != i) 18 | { 19 | swap(arr[i], arr[largest]); 20 | heapify(arr, n, largest); 21 | } 22 | } 23 | 24 | 25 | void heapSort(int arr[], int n) 26 | { 27 | 28 | for (int i = n / 2 - 1; i >= 0; i--) 29 | heapify(arr, n, i); 30 | 31 | 32 | for (int i=n-1; i>=0; i--) 33 | { 34 | swap(arr[0], arr[i]); 35 | 36 | heapify(arr, i, 0); 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | int arr[] = {12, 11, 13, 5, 6, 7}; 43 | int n = sizeof(arr)/sizeof(arr[0]); 44 | 45 | heapSort(arr, n); 46 | 47 | cout << "Sorted array is \n"; 48 | for (int i=0; i 2 | using namespace std; 3 | 4 | void bubbleSort(int * array, int size); 5 | 6 | int main(){ 7 | 8 | return 0; 9 | } 10 | 11 | void bubbleSort(int * array, int size){ 12 | for(int i = 0; i < size - 1; i++){ 13 | for(int j = 0; j < size - i - 1; j++){ 14 | if(array[j+1] < array[j]){ 15 | int tmp = array[j + 1]; 16 | array[j + 1] = array[j]; 17 | array[j] = tmp; 18 | } 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/bubble_sort.h: -------------------------------------------------------------------------------- 1 | #ifndef ALGORITHMS_BUBBLE_SORT_H 2 | #define ALGORITHMS_BUBBLE_SORT_H 3 | 4 | namespace algo { 5 | /** 6 | * runnig time of bubble sort is O(n^2) 7 | * @tparam Comparable 8 | * @param range 9 | */ 10 | template 11 | static void bubble_sort(vector &range) { 12 | bool swapped = true; 13 | while(swapped) { 14 | swapped = false; 15 | for (int i = 1; i < range.size() - 2; ++i) { 16 | if (range[i + 1] < range[i]) { 17 | swap(range[i + 1], range[i]); 18 | swapped = true; 19 | } 20 | } 21 | } 22 | } 23 | } 24 | 25 | #endif //ALGORITHMS_BUBBLE_SORT_H -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/insertion_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // perform insertion sort on arr[] 5 | void insertionSort(int arr[], int n) 6 | { 7 | // Start from second element (element at index 0 8 | // is already sorted) 9 | for (int i = 1; i < n; i++) 10 | { 11 | int value = arr[i]; 12 | int j = i; 13 | 14 | // Find the index j within the sorted subset arr[0..i-1] 15 | // where element arr[i] belongs 16 | while (j > 0 && arr[j - 1] > value) 17 | { 18 | arr[j] = arr[j - 1]; 19 | j--; 20 | } 21 | // Note that subarray arr[j..i-1] is shifted to 22 | // the right by one position i.e. arr[j+1..i] 23 | 24 | arr[j] = value; 25 | } 26 | } 27 | 28 | // Function to print n elements of the array arr 29 | void printArray(int arr[], int n) 30 | { 31 | for (int i = 0; i < n; i++) 32 | cout << arr[i] << " "; 33 | } 34 | 35 | int main() 36 | { 37 | int arr[] = { 3, 8, 5, 4, 1, 9, -2 }; 38 | int n = sizeof(arr) / sizeof(arr[0]); 39 | 40 | insertionSort(arr, n); 41 | 42 | // print the sorted array 43 | printArray(arr, n); 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/insertion_sort_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // recursive function to perform insertion sort on subarray arr[i..n] 5 | void insertionSort(int arr[], int i, int n) 6 | { 7 | int value = arr[i]; 8 | int j = i; 9 | // Find index j within the sorted subset arr[0..i-1] 10 | // where element arr[i] belongs 11 | while (j > 0 && arr[j - 1] > value) 12 | { 13 | arr[j] = arr[j - 1]; 14 | j--; 15 | } 16 | arr[j] = value; 17 | // Note that subarray arr[j..i-1] is shifted to 18 | // the right by one position i.e. arr[j+1..i] 19 | 20 | if (i + 1 <= n) 21 | insertionSort(arr, i + 1, n); 22 | } 23 | 24 | // Function to print n elements of the array arr 25 | void printArray(int arr[], int n) 26 | { 27 | for (int i = 0; i < n; i++) 28 | cout << arr[i] << " "; 29 | } 30 | 31 | int main() 32 | { 33 | int arr[] = { 3, 8, 5, 4, 1, 9, -2 }; 34 | int n = sizeof(arr) / sizeof(arr[0]); 35 | 36 | // Start from second element (element at index 0 37 | // is already sorted) 38 | insertionSort(arr, 1, n - 1); 39 | 40 | // print the sorted array 41 | printArray(arr, n); 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/merge_sort.h: -------------------------------------------------------------------------------- 1 | #ifndef ALGORITHMS_MERGE_SORT_H__ 2 | #define ALGORITHMS_MERGE_SORT_H__ 3 | 4 | namespace algo { 5 | 6 | template 7 | static void merge(vector &range, int left, int right) { 8 | // temp array to store and merge the two sorted parts. 9 | vector temp; 10 | 11 | int mid = (left + right) / 2; 12 | int left_pos = left; 13 | int right_pos = mid + 1; 14 | 15 | while (left_pos <= mid && right_pos <= right) { 16 | if (range[left_pos] < range[right_pos]) { 17 | temp.push_back(range[left_pos++]); 18 | } else { 19 | temp.push_back(range[right_pos++]); 20 | } 21 | } 22 | while (left_pos <= mid) temp.push_back(range[left_pos++]); 23 | while (right_pos <= right) temp.push_back(range[right_pos++]); 24 | 25 | // copy back the sorted array to the original one. 26 | for (int i = 0; i < temp.size(); ++i) { 27 | range[i + left] = temp[i]; 28 | } 29 | 30 | return; 31 | } 32 | 33 | /** 34 | * This is a typical divide and conquer algorithm. 35 | * the running time is O(nlgn). 36 | * @tparam Comparable 37 | * @param range 38 | */ 39 | template 40 | static void merge_sort(vector &range, int left, int right) { 41 | int mid = (left + right) / 2; 42 | if (left < right) { 43 | merge_sort(range, left, mid); 44 | merge_sort(range, mid + 1, right); 45 | merge(range, left, right); 46 | } 47 | return; 48 | } 49 | } 50 | 51 | #endif //ALGORITHMS_MERGE_SORT_H__ -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/merge_sorted_linkedlists: -------------------------------------------------------------------------------- 1 | /* 2 | Merge two sorted lists A and B as one linked list 3 | Node is defined as 4 | struct Node 5 | { 6 | int data; 7 | struct Node *next; 8 | } 9 | */ 10 | Node* MergeLists(Node *headA, Node* headB) 11 | { 12 | // This is a "method-only" submission. 13 | // You only need to complete this method 14 | Node *tempA=headA; 15 | Node *tempB=headB; 16 | Node *headC=NULL; 17 | Node *tempC=NULL; 18 | while(tempA!=NULL && tempB!=NULL) 19 | { 20 | Node *ptr=new Node; 21 | if(headC==NULL) 22 | { 23 | if(tempA->data < tempB->data) 24 | { 25 | ptr->data=tempA->data; 26 | tempA=tempA->next; 27 | } 28 | else 29 | { 30 | ptr->data=tempB->data; 31 | tempB=tempB->next; 32 | } 33 | ptr->next=NULL; 34 | headC=tempC=ptr; 35 | } 36 | else 37 | { 38 | if(tempA->data < tempB->data) 39 | { 40 | ptr->data=tempA->data; 41 | tempA=tempA->next; 42 | } 43 | else 44 | { 45 | ptr->data=tempB->data; 46 | tempB=tempB->next; 47 | } 48 | tempC->next=ptr; 49 | tempC=ptr; 50 | ptr->next=NULL; 51 | } 52 | } 53 | while(tempA!=NULL) 54 | { 55 | Node *ptr=new Node; 56 | ptr->data=tempA->data; 57 | ptr->next=NULL; 58 | if(headC==NULL) 59 | { 60 | headC=tempC=ptr; 61 | } 62 | else 63 | { 64 | tempC->next=ptr; 65 | tempC=ptr; 66 | } 67 | tempA=tempA->next; 68 | } 69 | while(tempB!=NULL) 70 | { 71 | Node *ptr=new Node; 72 | ptr->data=tempB->data; 73 | ptr->next=NULL; 74 | if(headC==NULL) 75 | { 76 | headC=tempC=ptr; 77 | } 78 | else 79 | { 80 | tempC->next=ptr; 81 | tempC=ptr; 82 | } 83 | tempB=tempB->next; 84 | } 85 | return headC; 86 | } 87 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/merging.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct node{ 4 | int data; 5 | struct node *next; 6 | }; 7 | 8 | node* create(int size){ 9 | struct node *start,*temp,*end,*p; 10 | p=new node; 11 | temp=start=p; 12 | int x; 13 | cin>>x; 14 | p->data=x; 15 | for(int i=1;inext=p; 18 | cin>>x; 19 | p->data=x; 20 | p->next= NULL; 21 | temp=p; 22 | } 23 | end=temp; 24 | return start; 25 | } 26 | void display(node *start){ 27 | node *p,*ptr; 28 | ptr=p=start; 29 | cout<data<<" "; 30 | while(ptr->next!=NULL){ 31 | ptr=ptr->next; 32 | cout<data<<" "; 33 | } 34 | } 35 | 36 | node* merge(node *p,node *s,int n,int m){ 37 | node *ptr,*start; 38 | if(n>0 and p->data < s->data){ 39 | start=ptr=p; 40 | p=p->next; 41 | } 42 | else if(m>0 and p->data >=s->data){ 43 | ptr=start=s; 44 | s=s->next; 45 | } 46 | else return p; 47 | int t=n+m-1; 48 | while(t--){ 49 | if(p==NULL){ 50 | ptr->next=s; 51 | return start; 52 | } 53 | else if(s==NULL){ 54 | ptr->next=p; 55 | return start; 56 | } 57 | else if(s->datadata){ 58 | ptr->next=s; 59 | s=s->next; 60 | ptr=ptr->next; 61 | } 62 | else { 63 | ptr->next=p; 64 | p=p->next; 65 | ptr=ptr->next; 66 | } 67 | } 68 | ptr->next=NULL; 69 | return start; 70 | } 71 | int main() 72 | { 73 | int n,m; 74 | node *p,*s; 75 | cin>>n; 76 | p=create(n); 77 | cin>>m; 78 | s=create(m); 79 | p=merge(p,s,n,m); 80 | display(p); 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/quick_sort.h: -------------------------------------------------------------------------------- 1 | #ifndef ALGORITHMS_QUICK_SORT_H__ 2 | #define ALGORITHMS_QUICK_SORT_H__ 3 | 4 | #include 5 | #include 6 | 7 | namespace algo { 8 | using namespace std; 9 | template 10 | static random_access_itr partitioning(random_access_itr p, random_access_itr r) { 11 | random_access_itr pivot = r; 12 | random_access_itr i = p - 1; 13 | for (random_access_itr j = p; j <= (r - 1); ++j) { 14 | if (*j < *pivot) { 15 | i++; 16 | swap(*j, *i); 17 | } 18 | } 19 | swap(*(i + 1), *pivot); 20 | return (i + 1); 21 | } 22 | 23 | template 24 | static void quick_sort(random_access_itr left, random_access_itr right) { 25 | if (distance(left, right) >= 1) { 26 | random_access_itr q = partitioning(left, right); 27 | quick_sort(q + 1, right); 28 | quick_sort(left, q - 1); 29 | } 30 | return; 31 | } 32 | } 33 | 34 | #endif //ALGORITHMS_QUICK_SORT_H__ -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/radixsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Radix Sort 2 | #include 3 | using namespace std; 4 | 5 | // A utility function to get maximum value in arr[] 6 | int getMax(int arr[], int n) 7 | { 8 | int mx = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > mx) 11 | mx = arr[i]; 12 | return mx; 13 | } 14 | 15 | // A function to do counting sort of arr[] according to 16 | // the digit represented by exp. 17 | void countSort(int arr[], int n, int exp) 18 | { 19 | int output[n]; // output array 20 | int i, count[10] = {0}; 21 | 22 | // Store count of occurrences in count[] 23 | for (i = 0; i < n; i++) 24 | count[ (arr[i]/exp)%10 ]++; 25 | 26 | // Change count[i] so that count[i] now contains actual 27 | // position of this digit in output[] 28 | for (i = 1; i < 10; i++) 29 | count[i] += count[i - 1]; 30 | 31 | // Build the output array 32 | for (i = n - 1; i >= 0; i--) 33 | { 34 | output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; 35 | count[ (arr[i]/exp)%10 ]--; 36 | } 37 | 38 | // Copy the output array to arr[], so that arr[] now 39 | // contains sorted numbers according to current digit 40 | for (i = 0; i < n; i++) 41 | arr[i] = output[i]; 42 | } 43 | 44 | // The main function to that sorts arr[] of size n using 45 | // Radix Sort 46 | void radixsort(int arr[], int n) 47 | { 48 | // Find the maximum number to know number of digits 49 | int m = getMax(arr, n); 50 | 51 | // Do counting sort for every digit. Note that instead 52 | // of passing digit number, exp is passed. exp is 10^i 53 | // where i is current digit number 54 | for (int exp = 1; m/exp > 0; exp *= 10) 55 | countSort(arr, n, exp); 56 | } 57 | 58 | // A utility function to print an array 59 | void print(int arr[], int n) 60 | { 61 | for (int i = 0; i < n; i++) 62 | cout << arr[i] << " "; 63 | } 64 | 65 | // Driver program to test above functions 66 | int main() 67 | { 68 | int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; 69 | int n = sizeof(arr)/sizeof(arr[0]); 70 | radixsort(arr, n); 71 | print(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // perform selection sort on arr[] 5 | void selectionSort(int arr[], int n) 6 | { 7 | // run (n - 1) times 8 | for (int i = 0; i < n - 1; i++) 9 | { 10 | // find the minimum element in the unsorted subarray[i..n-1] 11 | // and swap it with arr[i] 12 | int min = i; 13 | 14 | for (int j = i + 1; j < n; j++) 15 | { 16 | // if arr[j] element is less, then it is the new minimum 17 | if (arr[j] < arr[min]) 18 | min = j; // update index of min element 19 | } 20 | 21 | // swap the minimum element in subarray[i..n-1] with arr[i] 22 | swap(arr[min], arr[i]); 23 | } 24 | } 25 | 26 | // Function to print n elements of the array arr 27 | void printArray(int arr[], int n) 28 | { 29 | for (int i = 0; i < n; i++) 30 | cout << arr[i] << " "; 31 | } 32 | 33 | // main function 34 | int main() 35 | { 36 | int arr[] = { 3, 5, 8, 4, 1, 9, -2 }; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | 39 | selectionSort(arr, n); 40 | printArray(arr, n); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /cpp/Sorting_algorithms/selection_sort_recursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // recursive function to perform selection sort on subarray arr[i..n-1] 5 | void selectionSort(int arr[], int i, int n) 6 | { 7 | // find the minimum element in the unsorted subarray[i..n-1] 8 | // and swap it with arr[i] 9 | int min = i; 10 | for (int j = i + 1; j < n; j++) 11 | { 12 | // if arr[j] element is less, then it is the new minimum 13 | if (arr[j] < arr[min]) 14 | min = j; // update index of min element 15 | } 16 | 17 | // swap the minimum element in subarray[i..n-1] with arr[i] 18 | swap(arr[min], arr[i]); 19 | 20 | if (i + 1 < n) 21 | selectionSort(arr, i + 1, n); 22 | } 23 | 24 | // Function to print n elements of the array arr 25 | void printArray(int arr[], int n) 26 | { 27 | for (int i = 0; i < n; i++) 28 | cout << arr[i] << " "; 29 | } 30 | 31 | // main function 32 | int main() 33 | { 34 | int arr[] = { 3, 5, 8, 4, 1, 9, -2 }; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | 37 | selectionSort(arr, 0, n); 38 | printArray(arr, n); 39 | 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /cpp/detect_loop_linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | typedef struct node 5 | { 6 | int data; 7 | struct node *next; 8 | }node; 9 | 10 | node *newNode(int data) 11 | { 12 | node *p; 13 | p = (node*)malloc(sizeof(node)); 14 | p->data = data; // First node 15 | p->next = NULL; 16 | return p; 17 | } 18 | 19 | int main() 20 | { 21 | int len_loop; 22 | node *p , *q , *loop_node , *one_step , *two_steps , *length_calculator; 23 | p = newNode(1); 24 | p->next = newNode(2); 25 | p->next->next = newNode(3); 26 | p->next->next->next = newNode(4); 27 | loop_node = p->next->next->next; 28 | p->next->next->next->next = newNode(5); 29 | p->next->next->next->next->next = newNode(6); 30 | p->next->next->next->next->next->next = newNode(7); 31 | p->next->next->next->next->next->next->next = newNode(8); 32 | p->next->next->next->next->next->next->next->next = loop_node; 33 | //detect loop code 34 | one_step = p; 35 | two_steps = p; 36 | while(1) 37 | { 38 | if(one_step == NULL || two_steps == NULL) 39 | { 40 | printf("\n There is no loop"); 41 | break; 42 | } 43 | one_step = one_step->next; 44 | two_steps = two_steps->next->next; 45 | if(one_step == two_steps) 46 | { 47 | printf("\n There is a loop"); 48 | break; 49 | } 50 | } 51 | //find the length of the loop 52 | len_loop = 1; 53 | length_calculator = one_step->next; 54 | while(length_calculator!=one_step) 55 | { 56 | len_loop = len_loop+1; 57 | length_calculator = length_calculator->next; 58 | } 59 | printf("\n\n Length of the loop is %d",len_loop); 60 | //find the starting point of the loop 61 | // p is at the starting of the linked list 62 | q = one_step; 63 | while(p!=q) 64 | { 65 | p = p->next; 66 | q = q->next; 67 | } 68 | printf("\n The starting point of the loop is %d", p->data); 69 | return 0; 70 | } -------------------------------------------------------------------------------- /cpp/jump_search.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/yshshrm/Algorithms-And-Data-Structures/23a4e980f9dacce2c9624f50391bf60832f83908/cpp/jump_search.cpp -------------------------------------------------------------------------------- /cpp/kadane_maxSum_of_subarray.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define max(a, b)((a)>(b)?(a):(b)) 3 | 4 | int main(){ 5 | int n,i; 6 | scanf("%d", &n); 7 | int a[n]; 8 | for(i=0;i Results 8 | %%% where Results is a list matching the arity of input list Tasks 9 | %%% but contains the result of invoking Function on those tasks 10 | %%% @end 11 | %%%----------------------------------------------------------------------------- 12 | parallel(Function, Tasks) -> 13 | Pids = fork(Function, Tasks), 14 | join(Pids). 15 | 16 | %%------------------------------------------------------------------------------ 17 | %% @doc Forks all tasks in given list Tasks to new Erlang processes. Those 18 | %% processes invoke Function on forked tasks. 19 | %% @spec fork(Function, Tasks) -> Pids 20 | %% where Pids is a list of process IDs 21 | %% @end 22 | %%------------------------------------------------------------------------------ 23 | fork(Function, Tasks) -> 24 | Parent = self(), 25 | Pids = lists:map(fun(Task) -> 26 | spawn(fun() -> 27 | invoke(Parent, Function, Task) 28 | end) 29 | end, Tasks), 30 | Pids. 31 | 32 | join([P|Ps]) -> 33 | receive 34 | {P, Result} -> [Result|join(Ps)] 35 | end; 36 | join([]) -> 37 | []. 38 | 39 | invoke(Receiver, Function, Instance) -> 40 | Receiver ! {self(), (catch Function(Instance))}. 41 | -------------------------------------------------------------------------------- /erlang/README.md: -------------------------------------------------------------------------------- 1 | ### List of algorithms (Erlang) 2 | 3 | #### Task Forking & Joining 4 | 5 | * Fork / Join (`forkjoin.erl`) 6 | 7 | #### Sorting 8 | 9 | * Parallel Quicksort using Fork / Join (`pqsort.erl`) 10 | 11 | -------------------------------------------------------------------------------- /erlang/Sorting_algorithm/pqsort.erl: -------------------------------------------------------------------------------- 1 | -module(pqsort). 2 | 3 | -export([pqsort/1]). 4 | 5 | pqsort([]) -> []; 6 | pqsort([Pivot]) -> [Pivot]; 7 | pqsort([Pivot|Rest]) -> 8 | io:format("+", []), 9 | L = [X || X <- Rest, X < Pivot], 10 | R = [Y || Y <- Rest, Y >= Pivot], 11 | [SL, SR] = forkjoin:parallel(fun pqsort/1, [L,R]), 12 | io:format("-", []), 13 | SL ++ [Pivot] ++ SR. 14 | 15 | -------------------------------------------------------------------------------- /erlang/Sorting_algorithm/quicksort.erl: -------------------------------------------------------------------------------- 1 | -module(quicksort). 2 | -export([quicksort/2]). 3 | 4 | quicksort(_, []) -> 5 | []; 6 | quicksort(P, [Pivot | T]) -> 7 | quicksort(P, [X || X <- T, P(X, Pivot)]) ++ [Pivot] ++ quicksort(P, [X || X <- T, not P(X, Pivot)]). 8 | -------------------------------------------------------------------------------- /go/algs/Data_structures/linked-list.go: -------------------------------------------------------------------------------- 1 | package algs 2 | 3 | import "fmt" 4 | 5 | type LinkedList struct { 6 | head *listNode 7 | last *listNode 8 | size int 9 | } 10 | type listNode struct { 11 | val int 12 | next *listNode 13 | prev *listNode 14 | } 15 | func (l *LinkedList) Push(value int) int { 16 | return l.Add(value) 17 | } 18 | func (l *LinkedList) Pop() (int, bool) { 19 | if l.size == 0 { 20 | return 0, false 21 | } 22 | val := l.head.val 23 | if l.size == 1 { 24 | l.head = nil 25 | l.last = nil 26 | } else { 27 | l.head = l.head.next 28 | } 29 | l.size-- 30 | return val, true 31 | } 32 | func (l *LinkedList) Add(value int) int { 33 | newNode := listNode{val:value} 34 | if l.head == nil { 35 | l.head = &newNode 36 | l.last = l.head 37 | } else { 38 | l.last.next = &newNode 39 | newNode.prev = l.last 40 | l.last = &newNode 41 | } 42 | l.size++ 43 | return value 44 | } 45 | func (l *LinkedList) Remove(value int) bool { 46 | if l.size == 0 { 47 | return false 48 | } else if l.head.val == value { 49 | if l.size == 1 { 50 | l.head = nil 51 | l.last = nil 52 | } else { 53 | l.head.next.prev = nil 54 | l.head = l.head.next 55 | l.last = l.head 56 | } 57 | l.size-- 58 | return true 59 | } 60 | iter := l.head.next 61 | for iter != nil { 62 | if iter.val == value { 63 | if iter.next != nil { 64 | iter.prev.next = iter.next 65 | iter.next.prev = iter.prev 66 | } else { 67 | iter.prev.next = nil 68 | l.last = iter.prev 69 | } 70 | l.size-- 71 | return true 72 | } 73 | iter = iter.next 74 | } 75 | return false 76 | } 77 | func (l *LinkedList) find(value int) *listNode { 78 | if l.size == 0 { 79 | return nil 80 | } 81 | iter := l.head 82 | for iter != nil { 83 | if iter.val == value { 84 | return iter 85 | } 86 | iter = iter.next 87 | } 88 | return nil 89 | } 90 | func (l *LinkedList) Contains(value int) bool { 91 | if(l.find(value) != nil) { 92 | return true 93 | } else { 94 | return false 95 | } 96 | } 97 | func (l *LinkedList) Exchange(valueA int, valueB int) bool { 98 | valAnode := l.find(valueA) 99 | valBnode := l.find(valueB) 100 | if valAnode == nil || valBnode == nil { 101 | return false 102 | } 103 | valAnode.val = valueB 104 | valBnode.val = valueA 105 | return true 106 | } 107 | func (l *LinkedList) SwapPointers(valueA int, valueB int) bool { 108 | valAnode := l.find(valueA) 109 | valBnode := l.find(valueB) 110 | if valAnode == nil || valBnode == nil { 111 | return false 112 | } 113 | if valBnode.prev != nil { 114 | valBnode.prev.next = valAnode 115 | } else { 116 | l.head = valAnode 117 | } 118 | if valBnode.next != nil { 119 | valBnode.next.prev = valAnode 120 | } else { 121 | l.last = valAnode 122 | } 123 | if valAnode.prev != nil { 124 | valAnode.prev.next = valBnode 125 | } else { 126 | l.head = valBnode 127 | } 128 | if valAnode.next != nil { 129 | valAnode.next.prev = valBnode 130 | } else { 131 | l.last = valBnode 132 | } 133 | valAprev := valAnode.prev 134 | valAnext := valAnode.next 135 | valAnode.prev = valBnode.prev 136 | valAnode.next = valBnode.next 137 | valBnode.prev = valAprev 138 | valBnode.next = valAnext 139 | return true 140 | } 141 | func (l *LinkedList) PrintList() { 142 | iter := l.head 143 | for iter != nil { 144 | fmt.Println(iter.val) 145 | iter = iter.next 146 | } 147 | } -------------------------------------------------------------------------------- /go/algs/Search/search.go: -------------------------------------------------------------------------------- 1 | package algs 2 | 3 | func BinarySearch(arr [] int, val int) int { 4 | return binarySearch(arr, val, 0, len(arr)) 5 | } 6 | func binarySearch(arr [] int, val int, low int, high int) int { 7 | if low <= high { 8 | middle := low + (high - low) / 2 9 | if val < arr[middle] { 10 | return binarySearch(arr, val, 0, middle) 11 | } else if val > arr[middle] { 12 | return binarySearch(arr, val, middle + 1, high) 13 | } else { 14 | return middle 15 | } 16 | } 17 | return -1 18 | } 19 | func LinearSearch(arr [] int, val int) int { 20 | for i := 0; i < len(arr); i++ { 21 | if arr[i] == val { 22 | return i 23 | } 24 | } 25 | return -1 26 | } -------------------------------------------------------------------------------- /go/algs/Sorting_algorithm/Bubblesort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | /* 4 | Bubble sort 5 | */ 6 | 7 | import "fmt" 8 | 9 | 10 | func main() { 11 | arr := [5]int{2, 12, 7, 1, 43} 12 | fmt.Println("Initial array is:", arr) 13 | fmt.Println("") 14 | 15 | tmp := 0 16 | 17 | for i := 0; i < len(arr); i++ { 18 | for j := 0; j < len(arr) - 1; j++ { 19 | if arr[j] > arr[j + 1] { 20 | tmp = arr[j] 21 | arr[j] = arr[j + 1] 22 | arr[j + 1] = tmp 23 | } 24 | } 25 | } 26 | 27 | fmt.Println("Sorted array is: ", arr) 28 | } 29 | -------------------------------------------------------------------------------- /go/algs/Sorting_algorithm/mergeshort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func mergeSort(a []int) []int { 6 | 7 | if len(a) <= 1 { 8 | return a 9 | } 10 | 11 | left := make([]int, 0) 12 | right := make([]int, 0) 13 | m := len(a) / 2 14 | 15 | for i, x := range a { 16 | switch { 17 | case i < m: 18 | left = append(left, x) 19 | case i >= m: 20 | right = append(right, x) 21 | } 22 | } 23 | 24 | left = mergeSort(left) 25 | right = mergeSort(right) 26 | 27 | return merge(left, right) 28 | } 29 | 30 | func merge(left, right []int) []int { 31 | 32 | results := make([]int, 0) 33 | 34 | for len(left) > 0 || len(right) > 0 { 35 | if len(left) > 0 && len(right) > 0 { 36 | if left[0] <= right[0] { 37 | results = append(results, left[0]) 38 | left = left[1:len(left)] 39 | } else { 40 | results = append(results, right[0]) 41 | right = right[1:len(right)] 42 | } 43 | } else if len(left) > 0 { 44 | results = append(results, left[0]) 45 | left = left[1:len(left)] 46 | } else if len(right) > 0 { 47 | results = append(results, right[0]) 48 | right = right[1:len(right)] 49 | } 50 | } 51 | 52 | return results 53 | } 54 | 55 | func main() { 56 | 57 | arrayzor := []int{1, 6, 2, 4, 9, 0, 5, 3, 7, 8} 58 | fmt.Println("Unsorted array: ", arrayzor) 59 | arrayzor = mergeSort(arrayzor) 60 | fmt.Println("Sorted array: ", arrayzor) 61 | } 62 | -------------------------------------------------------------------------------- /haskell/factorial.hs: -------------------------------------------------------------------------------- 1 | main = print $ factorial 4 2 | 3 | factorial 0 = 1 4 | 5 | factorial n = factorial(n - 1) * n -------------------------------------------------------------------------------- /java/Data Structures/Graphs.java: -------------------------------------------------------------------------------- 1 | import java.util.Collection; 2 | import java.util.HashMap; 3 | import java.util.Set; 4 | 5 | public class Graphs { 6 | class Vertex { 7 | String name; 8 | HashMap neighbors; 9 | 10 | Vertex(String name) { 11 | this.name = name; 12 | this.neighbors = new HashMap<>(); 13 | } 14 | 15 | public boolean equals(Object other) { 16 | Vertex ov = (Vertex) other; 17 | return this.name.equals(ov.name); 18 | } 19 | 20 | public int hashCode() { 21 | return this.name.hashCode(); 22 | } 23 | 24 | public void display() { 25 | String rv = ""; 26 | rv = rv + this.name + "=>"; 27 | Set nbrs = this.neighbors.keySet(); 28 | for (Vertex nbr : nbrs) { 29 | rv = rv + nbr.name + "(" + this.neighbors.get(nbr) + "), "; 30 | } 31 | rv = rv + "END"; 32 | System.out.println(rv); 33 | 34 | } 35 | } 36 | 37 | private HashMap vertices; 38 | 39 | Graphs() { 40 | this.vertices = new HashMap<>(); 41 | } 42 | 43 | public int numberOfVertices() { 44 | return this.vertices.size(); 45 | } 46 | 47 | public void addVertex(String name) { 48 | if (this.vertices.containsKey(name)) { 49 | return; 50 | } 51 | Vertex vtx = new Vertex(name); 52 | this.vertices.put(name, vtx); 53 | } 54 | 55 | public void removeVertex(String name) { 56 | if (!this.vertices.containsKey(name)) { 57 | return; 58 | } 59 | Vertex vtx = this.vertices.get(name); 60 | Set nbrs = vtx.neighbors.keySet(); 61 | for (Vertex nbr : nbrs) { 62 | nbr.neighbors.remove(vtx); 63 | } 64 | this.vertices.remove(name); 65 | 66 | } 67 | 68 | public int numberOfEdges() { 69 | int size = 0; 70 | Collection vtces = this.vertices.values(); 71 | for (Vertex vtx : vtces) { 72 | size = size + vtx.neighbors.size(); 73 | } 74 | return size / 2; 75 | 76 | } 77 | 78 | public void addEdge(String v1, String v2, int weight) { 79 | Vertex vtx1 = this.vertices.get(v1); 80 | Vertex vtx2 = this.vertices.get(v2); 81 | if (vtx1 == null || vtx2 == null || vtx1.neighbors.containsKey(vtx2)) 82 | return; 83 | vtx1.neighbors.put(vtx2, weight); 84 | vtx2.neighbors.put(vtx1, weight); 85 | 86 | } 87 | 88 | public void removeEdge(String v1, String v2) { 89 | Vertex vtx1 = this.vertices.get(v1); 90 | Vertex vtx2 = this.vertices.get(v2); 91 | if (vtx1 == null || vtx2 == null || !vtx1.neighbors.containsKey(vtx2)) 92 | return; 93 | vtx1.neighbors.remove(vtx2); 94 | vtx2.neighbors.remove(vtx1); 95 | } 96 | 97 | public void display() { 98 | Set vtces = this.vertices.keySet(); 99 | for (String vtxname : vtces) { 100 | Vertex vtx = this.vertices.get(vtxname); 101 | vtx.display(); 102 | } 103 | System.out.println("------------------------------"); 104 | } 105 | 106 | public boolean hasPathRec(String v1, String v2) { 107 | Vertex vtx1 = this.vertices.get(v1); 108 | Vertex vtx2 = this.vertices.get(v2); 109 | if (vtx1 == null || vtx2 == null) 110 | return false; 111 | HashMap explored = new HashMap<>(); 112 | return this.hasPathRec(vtx1, vtx2, explored); 113 | } 114 | 115 | private boolean hasPathRec(Vertex vtx1, Vertex vtx2, HashMap explored) { 116 | boolean flag; 117 | if (vtx1.neighbors.containsKey(vtx2)) 118 | return true; 119 | if (explored.containsKey(vtx1)) 120 | return false; 121 | explored.put(vtx1, true); 122 | Set nbrs = vtx1.neighbors.keySet(); 123 | for (Vertex nbr : nbrs) { 124 | flag = hasPathRec(nbr, vtx2, explored); 125 | if (flag) 126 | return true; 127 | } 128 | return false; 129 | 130 | } 131 | 132 | public boolean isConnected() { 133 | Set keys = this.vertices.keySet(); 134 | for (String key : keys) { 135 | for (String vtx : keys) 136 | if (!hasPathRec(key, vtx)) { 137 | return false; 138 | } 139 | 140 | } 141 | return true; 142 | 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /java/Data Structures/HashMap.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | public class CustomizeHashMap { 4 | ArrayList> bucket; 5 | int bucketSize; 6 | int noOfEntries; 7 | 8 | public CustomizeHashMap() { 9 | bucket = new ArrayList<>(); 10 | bucketSize = 10; 11 | for (int i = 0; i < bucketSize; i++) { 12 | bucket.add(null); 13 | } 14 | noOfEntries = 0; 15 | } 16 | 17 | public void put(K key, V value) { 18 | int index = getIndex(key); 19 | MapNode head = bucket.get(index); 20 | 21 | while (head != null) { 22 | if (head.key.equals(key)) { 23 | head.value = value; 24 | return; 25 | } 26 | head = head.next; 27 | } 28 | MapNode nyaNode = new MapNode<>(key, value); 29 | nyaNode.next = bucket.get(index); 30 | noOfEntries++; 31 | bucket.set(index, nyaNode); 32 | 33 | if ((noOfEntries * (1.0)) / bucketSize > .7) { 34 | rehash(); 35 | } 36 | } 37 | 38 | 39 | 40 | 41 | private void rehash() { 42 | ArrayList> temp = bucket; 43 | bucketSize = bucketSize * 2; 44 | bucket = new ArrayList<>(); 45 | for (int i = 0; i < bucketSize; i++) { 46 | bucket.add(null); 47 | } 48 | noOfEntries = 0; 49 | for (MapNode head : temp) { 50 | while (head != null) { 51 | put(head.key, head.value); 52 | head = head.next; 53 | } 54 | } 55 | } 56 | 57 | private int getIndex(K key) { 58 | int hashCode = key.hashCode(); 59 | return compress(hashCode); 60 | } 61 | 62 | private int compress(int hashCode) { 63 | return hashCode % bucketSize; 64 | } 65 | 66 | public V get(K key) { 67 | int index = getIndex(key); 68 | MapNode head = bucket.get(index); 69 | 70 | while (head != null) { 71 | if (head.key.equals(key)) { 72 | return head.value; 73 | } 74 | head = head.next; 75 | } 76 | return null; 77 | } 78 | 79 | 80 | 81 | public boolean remove(K key) { 82 | 83 | int index = getIndex(key); 84 | MapNode head = bucket.get(index); 85 | 86 | if (head.key.equals(key)) { 87 | bucket.set(index, head.next); 88 | noOfEntries--; 89 | return true; 90 | } 91 | 92 | while (head != null) { 93 | if (head.next.key.equals(key)) { 94 | head.next = head.next.next; 95 | noOfEntries--; 96 | return true; 97 | } 98 | head = head.next; 99 | if (head.next == null) { 100 | break; 101 | } 102 | } 103 | return false; 104 | } 105 | 106 | public boolean isEmpty() { 107 | return noOfEntries == 0 ? true : false; 108 | } 109 | 110 | public int size() { 111 | return noOfEntries; 112 | } 113 | 114 | public ArrayList getKeys() { 115 | ArrayList keys = new ArrayList<>(); 116 | for (MapNode head : bucket) { 117 | while (head != null) { 118 | keys.add(head.key); 119 | head = head.next; 120 | } 121 | } 122 | return keys; 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /java/Data Structures/Heap.java: -------------------------------------------------------------------------------- 1 | package Lecture22; 2 | 3 | import java.util.ArrayList; 4 | 5 | public class Heap> { 6 | 7 | private ArrayList data; 8 | private boolean isMin; 9 | 10 | public Heap() { 11 | this(false); 12 | } 13 | 14 | public Heap(boolean isMin) { 15 | this.data = new ArrayList<>(); 16 | this.isMin = isMin; 17 | } 18 | 19 | public Heap(T[] items, boolean isMin) { 20 | this(isMin); 21 | 22 | for (T item : items) { 23 | this.data.add(item); 24 | } 25 | 26 | for (int i = this.data.size() / 2 - 1; i >= 0; i--) { 27 | this.downHeapify(i); 28 | } 29 | } 30 | 31 | public int size() { 32 | return this.data.size(); 33 | } 34 | 35 | public boolean isEmpty() { 36 | return this.data.size() == 0; 37 | } 38 | 39 | public void display() { 40 | this.displayNode(0); 41 | } 42 | 43 | private void displayNode(int idx) { 44 | int lci = 2 * idx + 1; 45 | int rci = 2 * idx + 2; 46 | 47 | String str = " "; 48 | 49 | if (lci < this.data.size()) { 50 | T lc = this.data.get(lci); 51 | str = lc + " => "; 52 | } else { 53 | str = "END => "; 54 | } 55 | 56 | T node = this.data.get(idx); 57 | str += node; 58 | 59 | if (rci < this.data.size()) { 60 | T rc = this.data.get(rci); 61 | str += " <= " + rc; 62 | } else { 63 | str += " <= END"; 64 | } 65 | 66 | System.out.println(str); 67 | 68 | if (lci < this.data.size()) { 69 | this.displayNode(lci); 70 | } 71 | 72 | if (rci < this.data.size()) { 73 | this.displayNode(rci); 74 | } 75 | 76 | } 77 | 78 | public T getHP() { 79 | return this.data.get(0); 80 | } 81 | 82 | public void add(T item) { 83 | this.data.add(item); 84 | 85 | upHeapify(this.data.size() - 1); 86 | 87 | } 88 | 89 | private void upHeapify(int ci) { 90 | if (ci == 0) { 91 | return; 92 | } 93 | 94 | int pi = (ci - 1) / 2; 95 | 96 | if (!isLarger(pi, ci)) { 97 | this.swap(pi, ci); 98 | this.upHeapify(pi); 99 | } 100 | } 101 | 102 | public T remove() { 103 | T rv = this.data.get(0); 104 | this.swap(0, this.data.size() - 1); 105 | this.data.remove(this.data.size() - 1); 106 | 107 | downHeapify(0); 108 | 109 | return rv; 110 | } 111 | 112 | private void downHeapify(int pi) { 113 | int lci = 2 * pi + 1; 114 | int rci = 2 * pi + 2; 115 | 116 | int mi = pi; 117 | 118 | if (lci < this.data.size() && isLarger(lci, mi)) { 119 | mi = lci; 120 | } 121 | 122 | if (rci < this.data.size() && isLarger(rci, mi)) { 123 | mi = rci; 124 | } 125 | if (pi != mi) { 126 | swap(mi, pi); 127 | downHeapify(mi); 128 | } 129 | } 130 | 131 | private void swap(int i, int j) { 132 | T temp = this.data.get(i); 133 | this.data.set(i, this.data.get(j)); 134 | this.data.set(j, temp); 135 | } 136 | 137 | private boolean isLarger(int i, int j) { 138 | T one = this.data.get(i); 139 | T two = this.data.get(j); 140 | 141 | if (this.isMin) { 142 | return one.compareTo(two) < 0; 143 | } else { 144 | return one.compareTo(two) > 0; 145 | } 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /java/Data Structures/MaxPriorityQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.NoSuchElementException; 3 | 4 | public class MaxPriorityQueue { 5 | private static final int DEFAULT_SIZE = 8; 6 | 7 | private V[] elements; 8 | private int elementsCount; 9 | private Comparator comparator; 10 | 11 | public MaxPriorityQueue() { 12 | this(DEFAULT_SIZE); 13 | } 14 | 15 | public MaxPriorityQueue(int length) { 16 | elements = (V[]) new Object[length + 1]; 17 | elementsCount = 0; 18 | } 19 | 20 | public MaxPriorityQueue(Comparator comparator) { 21 | this(DEFAULT_SIZE, comparator); 22 | } 23 | 24 | public MaxPriorityQueue(int length, Comparator comparator) { 25 | this(length); 26 | this.comparator = comparator; 27 | } 28 | 29 | public MaxPriorityQueue(V[] elements) { 30 | this(elements.length); 31 | elementsCount = elements.length; 32 | for (int i = 0; i < elementsCount; i++) { 33 | this.elements[i + 1] = elements[i]; 34 | } 35 | 36 | for (int sinkElementIndex = elementsCount / 2; sinkElementIndex >= 1; sinkElementIndex--) { 37 | sink(sinkElementIndex); 38 | } 39 | assert isMaxHeap(); 40 | } 41 | 42 | public void enqueue(V value) { 43 | if (elementsCount >= elements.length - 1) { 44 | resize(2 * elements.length); 45 | } 46 | elements[++elementsCount] = value; 47 | swim(elementsCount); 48 | assert isMaxHeap(); 49 | } 50 | 51 | public V dequeue() { 52 | if (isEmpty()) { 53 | throw new NoSuchElementException(); 54 | } 55 | V result = elements[1]; 56 | swap(1, elementsCount--); 57 | sink(1); 58 | elements[elementsCount + 1] = null; 59 | assert isMaxHeap(); 60 | return result; 61 | } 62 | 63 | public V peek() { 64 | if (isEmpty()) { 65 | throw new NoSuchElementException(); 66 | } 67 | return elements[1]; 68 | } 69 | 70 | public int size() { 71 | return elementsCount; 72 | } 73 | 74 | public boolean isEmpty() { 75 | return elementsCount == 0; 76 | } 77 | 78 | private void swim(int elementIndex) { 79 | while (elementIndex > 1 && less(elementIndex / 2, elementIndex)) { 80 | swap(elementIndex, elementIndex / 2); 81 | elementIndex /= 2; 82 | } 83 | } 84 | 85 | private void sink(int elementIndex) { 86 | while (2 * elementIndex <= elementsCount) { 87 | int greaterChildIndex = 2 * elementIndex; 88 | if (greaterChildIndex < elementsCount && less(greaterChildIndex, greaterChildIndex + 1)) { 89 | greaterChildIndex++; 90 | } 91 | 92 | if (!less(elementIndex, greaterChildIndex)) { 93 | break; 94 | } 95 | swap(elementIndex, greaterChildIndex); 96 | elementIndex = greaterChildIndex; 97 | } 98 | } 99 | 100 | private void resize(int newLength) { 101 | V[] newElements = (V[]) new Object[newLength]; 102 | for (int i = 1; i <= elementsCount; i++) { 103 | newElements[i] = elements[i]; 104 | } 105 | elements = newElements; 106 | } 107 | 108 | private boolean less(int i, int j) { 109 | if (comparator == null) { 110 | return ((Comparable) elements[i]).compareTo(elements[j]) < 0; 111 | } else { 112 | return comparator.compare(elements[i], elements[j]) < 0; 113 | } 114 | } 115 | 116 | private void swap(int i, int j) { 117 | V swap = elements[i]; 118 | elements[i] = elements[j]; 119 | elements[j] = swap; 120 | } 121 | 122 | private boolean isMaxHeap() { 123 | return isMaxHeap(1); 124 | } 125 | 126 | private boolean isMaxHeap(int parentIndex) { 127 | if (parentIndex > elementsCount) { 128 | return true; 129 | } 130 | 131 | int leftChildIndex = 2 * parentIndex; 132 | int rightChildIndex = 2 * parentIndex + 1; 133 | boolean leftChildGreaterThanParent = leftChildIndex <= elementsCount && less(parentIndex, leftChildIndex); 134 | boolean rightChildGreaterThanParent = rightChildIndex <= elementsCount && less(parentIndex, rightChildIndex); 135 | 136 | if (leftChildGreaterThanParent || rightChildGreaterThanParent) { 137 | return false; 138 | } 139 | 140 | return isMaxHeap(leftChildIndex) && isMaxHeap(rightChildIndex); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /java/Data Structures/MinPriorityQueue.java: -------------------------------------------------------------------------------- 1 | import java.util.Comparator; 2 | import java.util.NoSuchElementException; 3 | 4 | public class MinPriorityQueue { 5 | private static final int DEFAULT_SIZE = 8; 6 | 7 | private V[] elements; 8 | private int elementsCount; 9 | private Comparator comparator; 10 | 11 | public MinPriorityQueue() { 12 | this(DEFAULT_SIZE); 13 | } 14 | 15 | public MinPriorityQueue(int length) { 16 | elements = (V[]) new Object[length + 1]; 17 | elementsCount = 0; 18 | } 19 | 20 | public MinPriorityQueue(Comparator comparator) { 21 | this(DEFAULT_SIZE, comparator); 22 | } 23 | 24 | public MinPriorityQueue(int length, Comparator comparator) { 25 | this(length); 26 | this.comparator = comparator; 27 | } 28 | 29 | public MinPriorityQueue(V[] elements) { 30 | this(elements.length); 31 | elementsCount = elements.length; 32 | for (int i = 0; i < elementsCount; i++) { 33 | this.elements[i + 1] = elements[i]; 34 | } 35 | 36 | for (int sinkElementIndex = elementsCount / 2; sinkElementIndex >= 1; sinkElementIndex--) { 37 | sink(sinkElementIndex); 38 | } 39 | assert isMinHeap(); 40 | } 41 | 42 | public void enqueue(V value) { 43 | if (elementsCount >= elements.length - 1) { 44 | resize(2 * elements.length); 45 | } 46 | elements[++elementsCount] = value; 47 | swim(elementsCount); 48 | assert isMinHeap(); 49 | } 50 | 51 | public V dequeue() { 52 | if (isEmpty()) { 53 | throw new NoSuchElementException(); 54 | } 55 | V result = elements[1]; 56 | swap(1, elementsCount--); 57 | sink(1); 58 | elements[elementsCount + 1] = null; 59 | assert isMinHeap(); 60 | return result; 61 | } 62 | 63 | public V peek() { 64 | if (isEmpty()) { 65 | throw new NoSuchElementException(); 66 | } 67 | return elements[1]; 68 | } 69 | 70 | public int size() { 71 | return elementsCount; 72 | } 73 | 74 | public boolean isEmpty() { 75 | return elementsCount == 0; 76 | } 77 | 78 | private void swim(int elementIndex) { 79 | while (elementIndex > 1 && greater(elementIndex / 2, elementIndex)) { 80 | swap(elementIndex, elementIndex / 2); 81 | elementIndex /= 2; 82 | } 83 | } 84 | 85 | private void sink(int elementIndex) { 86 | while (2 * elementIndex <= elementsCount) { 87 | int smallerChildIndex = 2 * elementIndex; 88 | if (smallerChildIndex < elementsCount && greater(smallerChildIndex, smallerChildIndex + 1)) { 89 | smallerChildIndex++; 90 | } 91 | 92 | if (!greater(elementIndex, smallerChildIndex)) { 93 | break; 94 | } 95 | swap(elementIndex, smallerChildIndex); 96 | elementIndex = smallerChildIndex; 97 | } 98 | } 99 | 100 | private void resize(int newLength) { 101 | V[] newElements = (V[]) new Object[newLength]; 102 | for (int i = 1; i <= elementsCount; i++) { 103 | newElements[i] = elements[i]; 104 | } 105 | elements = newElements; 106 | } 107 | 108 | private boolean greater(int i, int j) { 109 | if (comparator == null) { 110 | return ((Comparable) elements[i]).compareTo(elements[j]) > 0; 111 | } else { 112 | return comparator.compare(elements[i], elements[j]) > 0; 113 | } 114 | } 115 | 116 | private void swap(int i, int j) { 117 | V swap = elements[i]; 118 | elements[i] = elements[j]; 119 | elements[j] = swap; 120 | } 121 | 122 | private boolean isMinHeap() { 123 | return isMinHeap(1); 124 | } 125 | 126 | private boolean isMinHeap(int parentIndex) { 127 | if (parentIndex > elementsCount) { 128 | return true; 129 | } 130 | 131 | int leftChildIndex = 2 * parentIndex; 132 | int rightChildIndex = 2 * parentIndex + 1; 133 | boolean leftChildLessThanParent = leftChildIndex <= elementsCount && greater(parentIndex, leftChildIndex); 134 | boolean rightChildLessThanParent = rightChildIndex <= elementsCount && greater(parentIndex, rightChildIndex); 135 | 136 | if (leftChildLessThanParent || rightChildLessThanParent) { 137 | return false; 138 | } 139 | 140 | return isMinHeap(leftChildIndex) && isMinHeap(rightChildIndex); 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /java/Data Structures/Minimum_Spanning_tree.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class MST 6 | { 7 | // Number of vertices in the graph 8 | private static final int V=5; 9 | 10 | // A utility function to find the vertex with minimum key 11 | // value, from the set of vertices not yet included in MST 12 | int minKey(int key[], Boolean mstSet[]) 13 | { 14 | // Initialize min value 15 | int min = Integer.MAX_VALUE, min_index=-1; 16 | 17 | for (int v = 0; v < V; v++) 18 | if (mstSet[v] == false && key[v] < min) 19 | { 20 | min = key[v]; 21 | min_index = v; 22 | } 23 | 24 | return min_index; 25 | } 26 | 27 | // A utility function to print the constructed MST stored in 28 | // parent[] 29 | void printMST(int parent[], int n, int graph[][]) 30 | { 31 | System.out.println("Edge Weight"); 32 | for (int i = 1; i < V; i++) 33 | System.out.println(parent[i]+" - "+ i+" "+ 34 | graph[i][parent[i]]); 35 | } 36 | 37 | // Function to construct and print MST for a graph represented 38 | // using adjacency matrix representation 39 | void primMST(int graph[][]) 40 | { 41 | // Array to store constructed MST 42 | int parent[] = new int[V]; 43 | 44 | // Key values used to pick minimum weight edge in cut 45 | int key[] = new int [V]; 46 | 47 | // To represent set of vertices not yet included in MST 48 | Boolean mstSet[] = new Boolean[V]; 49 | 50 | // Initialize all keys as INFINITE 51 | for (int i = 0; i < V; i++) 52 | { 53 | key[i] = Integer.MAX_VALUE; 54 | mstSet[i] = false; 55 | } 56 | 57 | // Always include first 1st vertex in MST. 58 | key[0] = 0; // Make key 0 so that this vertex is 59 | // picked as first vertex 60 | parent[0] = -1; // First node is always root of MST 61 | 62 | // The MST will have V vertices 63 | for (int count = 0; count < V-1; count++) 64 | { 65 | // Pick thd minimum key vertex from the set of vertices 66 | // not yet included in MST 67 | int u = minKey(key, mstSet); 68 | 69 | // Add the picked vertex to the MST Set 70 | mstSet[u] = true; 71 | 72 | // Update key value and parent index of the adjacent 73 | // vertices of the picked vertex. Consider only those 74 | // vertices which are not yet included in MST 75 | for (int v = 0; v < V; v++) 76 | 77 | // graph[u][v] is non zero only for adjacent vertices of m 78 | // mstSet[v] is false for vertices not yet included in MST 79 | // Update the key only if graph[u][v] is smaller than key[v] 80 | if (graph[u][v]!=0 && mstSet[v] == false && 81 | graph[u][v] < key[v]) 82 | { 83 | parent[v] = u; 84 | key[v] = graph[u][v]; 85 | } 86 | } 87 | 88 | // print the constructed MST 89 | printMST(parent, V, graph); 90 | } 91 | 92 | public static void main (String[] args) 93 | { 94 | /* Let us create a graph*/ 95 | MST t = new MST(); 96 | int graph[][] = new int[][] {{0, 2, 0, 6, 0}, 97 | {2, 0, 3, 8, 5}, 98 | {0, 3, 0, 0, 7}, 99 | {6, 8, 0, 0, 9}, 100 | {0, 5, 7, 9, 0}, 101 | }; 102 | 103 | // Print the solution 104 | t.primMST(graph); 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /java/Data Structures/PriorityQueue.java: -------------------------------------------------------------------------------- 1 | //////////////////////////////////////////////////////////////// 2 | class PriorityQ 3 | { 4 | private int maxSize; 5 | private long[] queArray; 6 | private int nItems; 7 | //------------------------------------------------------------- 8 | public PriorityQ(int s) 9 | { 10 | maxSize = s; 11 | queArray = new long[maxSize]; 12 | nItems = 0; 13 | } 14 | //------------------------------------------------------------- 15 | public void insert(long item) // insert item 16 | { 17 | int j; 18 | if(nItems==0) 19 | queArray[nItems++] = item; 20 | else 21 | { 22 | for(j=nItems-1; j>=0; j--) 23 | { 24 | if( item > queArray[j] ) 25 | queArray[j+1] = queArray[j]; 26 | else 27 | break; 28 | } 29 | queArray[j+1] = item; 30 | nItems++; 31 | } 32 | } 33 | //------------------------------------------------------------- 34 | public long remove() 35 | { return queArray[--nItems]; } 36 | //------------------------------------------------------------- 37 | public long peekMin() 38 | { return queArray[nItems-1]; } 39 | //------------------------------------------------------------- 40 | public boolean isEmpty() 41 | { return (nItems==0); } 42 | //------------------------------------------------------------- 43 | public boolean isFull() 44 | { return (nItems == maxSize); } 45 | //------------------------------------------------------------- 46 | } 47 | -------------------------------------------------------------------------------- /java/Data Structures/SegmentTree.java: -------------------------------------------------------------------------------- 1 | /** 2 | * 3 | * @author Mohamed Mashaal (https://github.com/mohamedmashaal) 4 | * 5 | */ 6 | 7 | public class SegmentTree { 8 | private int [] st; 9 | private Integer [] A ; 10 | private int n ; 11 | 12 | public SegmentTree(Integer [] A) { 13 | this.A = A ; 14 | n = A.length; 15 | st = new int [4*n]; 16 | build(1,0,n-1); 17 | } 18 | 19 | public int rmq(int i , int j) { 20 | return rmq(1,0,n-1,i,j); 21 | } 22 | 23 | private int left(int p) { 24 | return p << 1 ; 25 | } 26 | private int right(int p) { 27 | return (p << 1)+1 ; 28 | } 29 | private void build(int p, int L, int R) { 30 | if(L == R) 31 | st[p] = L ; 32 | else { 33 | build(left(p) ,L , (L+R)/2); 34 | build(right(p) ,(L+R)/2 +1 , R); 35 | int p1 = st[left(p)] , p2 = st[right(p)]; 36 | st[p] = (A[p1] <= A[p2]) ? p1 : p2 ; 37 | } 38 | } 39 | 40 | private int rmq(int p , int L , int R , int i , int j ) { 41 | if(i > R || j < L) return -1 ; 42 | if(L >= i && R <= j) return st[p]; 43 | 44 | int p1 = rmq(left(p) , L , (L+R)/2 ,i , j); 45 | int p2 = rmq(right(p) , (L+R)/2 + 1 , R , i , j); 46 | 47 | if (p1 == -1) return p2 ; 48 | if (p2 == -1) return p1 ; 49 | return (A[p1] <= A[p2]) ? p1 : p2 ; 50 | } 51 | 52 | public static void main(String [] args) { 53 | Integer [] A = {18,17,13,19,15,11,20}; 54 | SegmentTree tree = new SegmentTree(A); 55 | System.out.println(tree.rmq(1, 3)); 56 | System.out.println(tree.rmq(4, 6)); 57 | } 58 | } -------------------------------------------------------------------------------- /java/Data Structures/Stack.java: -------------------------------------------------------------------------------- 1 | public class Stack{ 2 | 3 | int arr[]; 4 | 5 | int size; 6 | 7 | public Stack(int size) { 8 | arr = new int[size]; 9 | this.size = 0; 10 | } 11 | 12 | public boolean isEmpty(){ return size == 0; } 13 | 14 | public int top() throws StackEmptyException{ 15 | if(isEmpty()) 16 | throw new StackEmptyException(); 17 | return arr[size - 1]; 18 | } 19 | 20 | public int size(){ return size; } 21 | 22 | public void push(int element) throws StackFullException { 23 | if(size == arr.length) 24 | throw new StackFullException(); 25 | arr[size++] = element; 26 | } 27 | 28 | public int pop() throws StackEmptyException { 29 | if(isEmpty()) 30 | throw new StackEmptyException(); 31 | return arr[--size]; 32 | } 33 | } 34 | 35 | class StackFullException extends Exception{} 36 | 37 | class StackEmptyException extends Exception{} 38 | -------------------------------------------------------------------------------- /java/Data Structures/Tries.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Set; 4 | 5 | public class Tries { 6 | 7 | private class Node { 8 | Character data; 9 | HashMap children; 10 | boolean isTerminal; 11 | 12 | public Node(Character data, boolean isTerminal) { 13 | this.data = data; 14 | this.children = new HashMap<>(); 15 | this.isTerminal = false; 16 | } 17 | 18 | } 19 | 20 | private int numWords; 21 | private Node root; 22 | 23 | public Tries() { 24 | this.numWords = 0; 25 | this.root = new Node('\0', false); 26 | } 27 | 28 | public int numWords() { 29 | return this.numWords; 30 | } 31 | 32 | public boolean isEmpty() { 33 | return this.numWords() == 0; 34 | } 35 | 36 | public void add(String str) { 37 | this.add(str, root); 38 | } 39 | 40 | private void add(String str, Node parent) { 41 | if (str.length() == 0) { 42 | if (parent.isTerminal) { 43 | } else { 44 | parent.isTerminal = true; 45 | this.numWords++; 46 | 47 | } 48 | return; 49 | } 50 | String ros = str.substring(1); 51 | char cc = str.charAt(0); 52 | Node child = parent.children.get(cc); 53 | if (child == null) { 54 | child = new Node(cc, false); 55 | parent.children.put(cc, child); 56 | this.add(ros, child); 57 | } else { 58 | this.add(ros, parent.children.get(cc)); 59 | 60 | } 61 | } 62 | 63 | public void display() { 64 | this.display(this.root, ""); 65 | } 66 | 67 | private void display(Node node, String osf) { 68 | if (node.isTerminal) { 69 | String toPrint = osf.substring(1) + node.data; 70 | System.out.println(toPrint); 71 | } 72 | Set> entries = node.children.entrySet(); 73 | for (Map.Entry entry : entries) 74 | this.display(entry.getValue(), osf + node.data); 75 | 76 | } 77 | 78 | public boolean search(String str) { 79 | return this.search(str, root); 80 | } 81 | 82 | private boolean search(String str, Node node) { 83 | if (str.length() == 0) { 84 | if (node.isTerminal) 85 | return true; 86 | else 87 | return false; 88 | } 89 | char cc = str.charAt(0); 90 | String ros = str.substring(1); 91 | Node child = node.children.get(cc); 92 | if (child == null) 93 | return false; 94 | return this.search(ros, child); 95 | 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /java/Data Structures/binary_search_tree.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | Node left; 3 | Node right; 4 | int value; 5 | 6 | Node(int value){ 7 | this.value = value; 8 | } 9 | } 10 | 11 | public void search(Node node, int key) { 12 | if (node.value == key || n == null) { 13 | System.out.println("Value is found"); 14 | } else if (key < node.value) { 15 | search(n.left, key); 16 | } else { 17 | search(n.right, key); 18 | } 19 | } -------------------------------------------------------------------------------- /java/Data Structures/binary_tree.java: -------------------------------------------------------------------------------- 1 | class Node { 2 | 3 | Node left, right; 4 | int data; 5 | 6 | public Node() { 7 | left = null; 8 | right = null; 9 | data = 0; 10 | } 11 | 12 | public BTNode(int n) { 13 | left = null; 14 | right = null; 15 | data = n; 16 | } 17 | 18 | public void setLeft(Node n) { 19 | left = n; 20 | } 21 | 22 | public void setRight(Node n) { 23 | right = n; 24 | } 25 | 26 | public Node getLeft() { 27 | return left; 28 | } 29 | 30 | public Node getRight() { 31 | return right; 32 | } 33 | 34 | public void setData(int d) { 35 | data = d; 36 | } 37 | 38 | public int getData() { 39 | return data; 40 | } 41 | } 42 | 43 | class BinaryTree { 44 | 45 | private Node root; 46 | 47 | public BinaryTree() { 48 | root = null; 49 | } 50 | 51 | public boolean isEmpty() { 52 | return root == null; 53 | } 54 | 55 | public void insert(int data) { 56 | root = insert(root, data); 57 | } 58 | 59 | private Node insert(Node node, int data) 60 | { 61 | if (node == null) 62 | node = new Node(data); 63 | else 64 | { 65 | if (node.getRight() == null) 66 | node.right = insert(node.right, data); 67 | else 68 | node.left = insert(node.left, data); 69 | } 70 | return node; 71 | } 72 | 73 | public int countNodes() { 74 | return countNodes(root); 75 | } 76 | 77 | private int countNodes(Node r) { 78 | if (r == null) 79 | return 0; 80 | else 81 | { 82 | int l = 1; 83 | l += countNodes(r.getLeft()); 84 | l += countNodes(r.getRight()); 85 | return l; 86 | } 87 | } 88 | } -------------------------------------------------------------------------------- /java/Data Structures/generic_linked_list.java: -------------------------------------------------------------------------------- 1 | public class LinkedList { 2 | 3 | private LinkedListNode first = null; 4 | 5 | public void insert(LinkedListNode node) { 6 | node.setNext(first); 7 | first = node; 8 | } 9 | 10 | public void remove() { 11 | first = first.getNext != null ? first.getNext : null; 12 | } 13 | 14 | private void printList(LinkedListNode node) { 15 | System.out.println("Node is " + node.getValue()); 16 | if(node.getNext() != null) printList(node.getNext); 17 | } 18 | 19 | public void print() { 20 | printList(first); 21 | } 22 | } 23 | 24 | class LinkedListNode { 25 | 26 | private T value; 27 | private LinkedListNode next; 28 | 29 | public LinkedListNode(T value) { 30 | this.value; 31 | } 32 | 33 | public void setNext(LinkedListNode next) { 34 | this.next = next; 35 | } 36 | 37 | public LinkedListNode getNext { 38 | return next; 39 | } 40 | 41 | public T getValue() { 42 | return value; 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /java/Data Structures/queue.java: -------------------------------------------------------------------------------- 1 | public class Queue { 2 | private int size; 3 | private int[] queueArr; 4 | private int front = -1; 5 | private int rear = -1; 6 | private int totalItems; 7 | 8 | public TNQueue(int s) { 9 | size = s; 10 | queueArr = new int[s]; 11 | } 12 | 13 | public void insert(int i) { 14 | rear++; 15 | System.out.println("Inserting "+i); 16 | queueArr[rear] = i; 17 | totalItems++; 18 | } 19 | 20 | public int remove() { 21 | front++; 22 | totalItems--; 23 | System.out.println("Removing "+queueArr[front]); 24 | return queueArr[front]; 25 | } 26 | 27 | public boolean isFull() { 28 | return (totalItems == size); 29 | } 30 | 31 | public boolean isEmpty() { 32 | return (totalItems == 0); 33 | } 34 | } -------------------------------------------------------------------------------- /java/Fibonacci.java: -------------------------------------------------------------------------------- 1 | public class Fibonacci { 2 | public static long fibonacci(final int n) { 3 | if (n <= 1) { 4 | return n; 5 | } else { 6 | return fibonacci(n-1) + fibonacci(n-2); 7 | } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /java/FibonnaciDP.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | 4 | public class FibonnaciDP { 5 | static Map fib = new HashMap<>(); 6 | 7 | public static long fibonnaciTopDown(int arg) { 8 | if (arg == 0 || arg == 1) { 9 | fib.put(arg, (long) arg); 10 | } 11 | if (!fib.containsKey(arg)) { 12 | fib.put(arg, fibonnaciTopDown(arg - 1) + fibonnaciTopDown(arg - 2)); 13 | } 14 | return fib.get(arg); 15 | } 16 | 17 | public static long fibonnaciBottomUp(int arg) { 18 | int dp[] = new int[arg + 1]; 19 | dp[0] = 0; 20 | dp[1] = 1; 21 | for (int i = 2; i <= arg; i++) { 22 | dp[i] = dp[i - 1] + dp[i - 2]; 23 | } 24 | return dp[arg]; 25 | } 26 | } -------------------------------------------------------------------------------- /java/FloydAlgo.java: -------------------------------------------------------------------------------- 1 | /* 2 | Linked List is a data structure having link or address to the next and/or previous 3 | node along with some data. Floyd's algorithm is used to find a loop in a liked list. 4 | For this 2 pointers are used a slow pointer which moves by one and a fast pointer which 5 | moves by two. If loop is present the fast and slow pointer will meet at a node thus 6 | helping in loop detection*/ 7 | class FloydAlgo { 8 | public boolean findLoop(Node head) 9 | { 10 | Node slow = head, fast = head; 11 | while (slow != null && fast != null && fast.next != null) { 12 | slow = slow.next; 13 | fast = fast.next.next; 14 | if (slow == fast) 15 | return true;//Loop is found 16 | return false; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /java/GreatestCommonDivisor.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * In mathematics, the greatest common divisor (gcd) of two or more integers, when at least one of them is not 4 | * zero, is the largest positive integer that is a divisor of both numbers. 5 | * 6 | * @see Greatest Common Divisor (Wikipedia) 7 | */ 8 | public class GreatestCommonDivisor { 9 | 10 | /** 11 | * Calculate greatest common divisor of two numbers using recursion. 12 | */ 13 | public static long gcdUsingRecursion(long a, long b) { 14 | a = Math.abs(a); 15 | b = Math.abs(b); 16 | return a == 0 ? b : gcdUsingRecursion(b%a, a); 17 | } 18 | 19 | /** 20 | * A much more efficient method is the Euclidean algorithm, which uses a division algorithm such as long division 21 | * in combination with the observation that the gcd of two numbers also divides their difference. 22 | * @see Euclidean Algorithm (Wikipedia) 23 | */ 24 | public static final long gcdUsingEuclides(long x, long y) { 25 | long greater = x; 26 | long smaller = y; 27 | if (y > x) { 28 | greater = y; 29 | smaller = x; 30 | } 31 | 32 | long result = 0; 33 | while (true) { 34 | if (smaller == greater) { 35 | result = smaller; // smaller == greater 36 | break; 37 | } 38 | 39 | greater -= smaller; 40 | if (smaller > greater) { 41 | long temp = smaller; 42 | smaller = greater; 43 | greater = temp; 44 | } 45 | } 46 | return result; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /java/PalindromeNumber.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | class Test{ 3 | public void PalindromeNumber(int num){ 4 | int n=0,digit,rev=0; 5 | n=num; 6 | do{ 7 | digit=num%10; 8 | rev=(rev*10)+digit; 9 | num=num/10; 10 | }while(num!=0); 11 | 12 | System.out.println("The reverse number is : "+rev); 13 | if(rev==num) 14 | System.out.println("The number is Palindrome"); 15 | else 16 | System.out.println("The number is Not Palindrome"); 17 | } 18 | 19 | public static void public static void main(String[] args) { 20 | Test obj = new Test(); 21 | BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 22 | int num; 23 | try{ 24 | System.out.println("Enter a number : "); 25 | num=Integer.parseInt(br.readLine()); 26 | obj.PalindromeNumber(num); 27 | } 28 | catch(Exception e){ 29 | System.out.println(e); 30 | } 31 | 32 | } 33 | } -------------------------------------------------------------------------------- /java/PrimeNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class PrimeNumber { 4 | 5 | // Sieve_of_Eratosthenes Method 6 | private static boolean[] primes = null; // Initialization of an array containing whether number is prime or not 7 | 8 | /** 9 | * @see Sieve of Eratosthenes (Wikipedia) 10 | */ 11 | public static final boolean isPrime(int number) { 12 | if (number == 1) { 13 | return false; 14 | } 15 | if (primes == null || number >= primes.length) { 16 | int start = 2; 17 | 18 | if (primes == null) { 19 | primes = new boolean[number + 1]; // Creating a new Array upto N numbers 20 | } else if (number >= primes.length) { 21 | primes = Arrays.copyOf(primes, number + 1); 22 | } 23 | /** 24 | * Finding the values of the prime boolean array 25 | */ 26 | for (int i = start; i <= Math.sqrt(number); i++) { 27 | if (!primes[i]) { 28 | for (int j = i * 2; j <= number; j += i) { 29 | primes[j] = true; 30 | } 31 | } 32 | } 33 | } 34 | return !primes[number]; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /java/PrintArmstrongNo.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class ArmstrongNo { 4 | 5 | public static void main(String[] args) { 6 | // TODO Auto-generated method stub 7 | Scanner scn = new Scanner(System.in); 8 | System.out.println("Enter Two Numbers"); 9 | int a = scn.nextInt(); 10 | int b = scn.nextInt(); 11 | 12 | while (a<=b) 13 | { 14 | 15 | int n = a; 16 | int c = 0; 17 | while (n!=0) 18 | { 19 | int rem = n % 10; 20 | c = c + (rem*rem*rem); 21 | n /= 10; 22 | } 23 | if (c == a) 24 | { 25 | System.out.print(c + " "); 26 | } 27 | a++; 28 | } 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /java/Remove Stop Words in given text file/StopWords.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.util.Formatter; 3 | import java.util.Scanner; 4 | class Five{ 5 | public static void main(String [] args){ 6 | String []a=new String[50]; 7 | Scanner w=new Scanner(System.in); 8 | int i=0,c=0,l,h; 9 | String b; 10 | System.out.println("enter no of stop words");//input to take no of stop words 11 | h=w.nextInt(); 12 | 13 | String [] d=new String[h]; 14 | System.out.println("enter "+h+" stop characters"); 15 | for(l=0;l= low) { 17 | int mid = low + (hi - low) / 2; 18 | if (query == arr[mid]) { 19 | return mid; 20 | } else if (query < arr[mid]) { 21 | return leftBinarySearch(arr, low, mid - 1, query); 22 | } else if (query > arr[mid]) { 23 | return leftBinarySearch(arr, mid + 1, hi, query); 24 | } 25 | } 26 | return -1; 27 | } 28 | 29 | public static int rightBinarySearch(int arr[], int low, int hi, int query) { 30 | if (hi >= low) { 31 | int mid = low + (hi - low) / 2; 32 | if (query == arr[mid]) { 33 | return mid; 34 | } else if (query > arr[mid]) { 35 | return rightBinarySearch(arr, low, mid - 1, query); 36 | } else if (query < arr[mid]) { 37 | return rightBinarySearch(arr, mid + 1, hi, query); 38 | } 39 | } 40 | return -1; 41 | } 42 | 43 | public static int bitonicMax(int arr[], int low, int high) { 44 | if (low == high) { 45 | return low; 46 | } 47 | int mid = low + (high - low) / 2; 48 | if (arr[mid] < arr[mid + 1]) { 49 | return bitonicMax(arr, mid + 1, high); 50 | } 51 | if (arr[mid] > arr[mid + 1]) { 52 | return bitonicMax(arr, low, mid); 53 | } 54 | return mid; 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /java/Search/IntArrayLinearSearch.java: -------------------------------------------------------------------------------- 1 | 2 | package intsearch; 3 | 4 | /** 5 | * 6 | * @author PanosPapastergiou 7 | */ 8 | public class IntArrayLinearSearch { 9 | 10 | public int Search(int a[],int size,int b){ 11 | int temp; 12 | for (int i=0;i sortedArray[mid]) { 14 | return recursiveBinarySearch(sortedArray, mid + 1, end, key); 15 | 16 | } else { 17 | return mid; 18 | } 19 | } 20 | return -(start + 1); 21 | } 22 | 23 | public static void main(String[] args) { 24 | 25 | int[] arr1 = {2, 45, 234, 567, 876, 900, 976, 999}; 26 | int index = recursiveBinarySearch(arr1, 0, arr1.length, 45); 27 | System.out.println("Found 45 at " + index + " index"); 28 | index = recursiveBinarySearch(arr1, 0, arr1.length, 999); 29 | System.out.println("Found 999 at " + index + " index"); 30 | index = recursiveBinarySearch(arr1, 0, arr1.length, 876); 31 | System.out.println("Found 876 at " + index + " index"); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /java/Search/binary_search.java: -------------------------------------------------------------------------------- 1 | public class BinarySearch { 2 | public boolean search(int arr[], int key){ 3 | int low = 0; 4 | int high = arr.length - 1; 5 | int mid, swap; 6 | 7 | for(int i=arr.length-1; i>0; i--) 8 | for(int j=0; j arr[j+1]){===5y4w rhgwsdserd 10 | swap = arr[j]; 11 | arr[j] = arr[j+1]; 12 | arr[j+1] = swap; 13 | } 14 | } 15 | 16 | while(low <= high){ 17 | mid = (low + high) / 2; 18 | 19 | if(arr[mid] == key) 20 | return true; 21 | else if(key > arr[mid]) 22 | low = mid + 1; 23 | else if(key < arr[mid]) 24 | high = mid - 1; 25 | } 26 | return false; 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /java/Search/jumpsearch.java: -------------------------------------------------------------------------------- 1 | public class JumpSearch 2 | { 3 | public static int jumpSearch(int[] arr, int x) 4 | { 5 | int n = arr.length; 6 | 7 | // Finding block size to be jumped 8 | int step = (int)Math.floor(Math.sqrt(n)); 9 | 10 | // Finding the block where element is 11 | // present (if it is present) 12 | int prev = 0; 13 | while (arr[Math.min(step, n)-1] < x) 14 | { 15 | prev = step; 16 | step += (int)Math.floor(Math.sqrt(n)); 17 | if (prev >= n) 18 | return -1; 19 | } 20 | 21 | // Doing a linear search for x in block 22 | // beginning with prev. 23 | while (arr[prev] < x) 24 | { 25 | prev++; 26 | 27 | // If we reached next block or end of 28 | // array, element is not present. 29 | if (prev == Math.min(step, n)) 30 | return -1; 31 | } 32 | 33 | // If element is found 34 | if (arr[prev] == x) 35 | return prev; 36 | 37 | return -1; 38 | } 39 | 40 | public static void main(String [ ] args) 41 | { 42 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 43 | 34, 55, 89, 144, 233, 377, 610}; 44 | int x = 55; 45 | 46 | // Find the index of 'x' using Jump Search 47 | int index = jumpSearch(arr, x); 48 | 49 | // Print the index where 'x' is located 50 | System.out.println("\nNumber " + x + 51 | " is at index " + index); 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /java/Search/linear_search(string).java: -------------------------------------------------------------------------------- 1 | /* 2 | * To change this license header, choose License Headers in Project Properties. 3 | * To change this template file, choose Tools | Templates 4 | * and open the template in the editor. 5 | */ 6 | 7 | /** 8 | * 9 | * @author Solon 10 | */ 11 | public class Search { 12 | 13 | static public Boolean LinearSearch(String[] table,String key) 14 | { 15 | for(int i=0;ia[j]) 42 | { 43 | temp=a[i]; 44 | a[i]=a[j]; 45 | a[j]=temp; 46 | } 47 | } 48 | } 49 | } 50 | public static void bubbleSort() 51 | { 52 | int temp; 53 | for(int i=0; ia[j+1]) 58 | { 59 | temp=a[j]; 60 | a[j]=a[j+1]; 61 | a[j+1]=temp; 62 | } 63 | } 64 | } 65 | } 66 | public static void display() 67 | { 68 | for(int i=0;i= 0; i--) 16 | heapify(arr, n, i); 17 | 18 | for (int i=n-1; i>=0; i--){ 19 | //Moving current root to the end. 20 | int temp = arr[0]; 21 | arr[0] = arr[i]; 22 | arr[i] = temp; 23 | 24 | //call Max heapify on the remaining heap. 25 | heapify(arr, i, 0); 26 | } 27 | } 28 | 29 | void heapify(int arr[], int n, int i){ 30 | //init 31 | int largest = i; 32 | int l = 2*i + 1; 33 | int r = 2*i + 2; 34 | 35 | //if left child is larger than root, largest =left. 36 | if (l < n && arr[l] > arr[largest]) 37 | largest = l; 38 | //if right child is larger than largest, largest =right 39 | if (r < n && arr[r] > arr[largest]) 40 | largest = r; 41 | 42 | //if largest is not root. 43 | if (largest != i){ 44 | 45 | //rearrange the heap. 46 | int swap = arr[i]; 47 | arr[i] = arr[largest]; 48 | arr[largest] = swap; 49 | 50 | //Recursively heapify. 51 | heapify(arr, n, largest); 52 | } 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /java/Sorts/InsertionSortGenerics.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | import java.util.Random; 3 | 4 | public class InsertionSort { 5 | 6 | public static > void sort(E[] array) { 7 | if (array == null || array.length < 2) { return; } 8 | 9 | for (int i = 1; i < array.length; i++) { 10 | int j = i; 11 | E val = array[j]; 12 | while (j > 0 && val.compareTo(array[j - 1]) < 0) { 13 | array[j] = array[j - 1]; 14 | j = j - 1; 15 | } 16 | if (j != i) { 17 | array[j] = val; 18 | } 19 | } 20 | } 21 | 22 | public static void main(String[] args) { 23 | final int LEN = 15; 24 | final int MAX_RANDOM = 100; 25 | final Integer[] ar = new Integer[LEN]; 26 | Random rnd = new Random(); 27 | for (int i = 0; i < LEN; i++) { 28 | ar[i] = new Integer(rnd.nextInt(MAX_RANDOM)); 29 | } 30 | System.out.println(Arrays.toString(ar)); 31 | 32 | sort(ar); 33 | System.out.println(Arrays.toString(ar)); 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /java/Sorts/SelectionSort.java: -------------------------------------------------------------------------------- 1 | public class SelectionSort { 2 | 3 | public > void selectionSort(E[] arr){ 4 | int i, j; 5 | int min; 6 | E tmp; 7 | 8 | if(arr.length == 0) return; 9 | 10 | for(i = 0; i < arr.length-1; i++){ 11 | min = i; //suppose that the first number of our subarray is the smallest 12 | for(j = i+1; j < arr.length; j++){ 13 | if(arr[j].compareTo(arr[min]) < 0) min = j; //if I find a smaller number I update the variable min 14 | } 15 | if(arr[min].compareTo(arr[i]) != 0){//if a swap is needed... 16 | tmp = arr[min]; //i swap the position of the first number of the subarray... 17 | arr[min] = arr[i]; //with the smallest number of the subarray 18 | arr[i] = tmp; 19 | } 20 | } 21 | return; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Sorts/TopologicalSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | // This class represents a directed graph using adjacency 5 | // list representation 6 | class Graph 7 | { 8 | private int V; // No. of vertices 9 | private LinkedList adj[]; // Adjacency List 10 | 11 | //Constructor 12 | Graph(int v) 13 | { 14 | V = v; 15 | adj = new LinkedList[v]; 16 | for (int i=0; i it = adj[v].iterator(); 33 | while (it.hasNext()) 34 | { 35 | i = it.next(); 36 | if (!visited[i]) 37 | topologicalSortUtil(i, visited, stack); 38 | } 39 | 40 | // Push current vertex to stack which stores result 41 | stack.push(new Integer(v)); 42 | } 43 | 44 | // The function to do Topological Sort. It uses 45 | // recursive topologicalSortUtil() 46 | void topologicalSort() 47 | { 48 | Stack stack = new Stack(); 49 | 50 | // Mark all the vertices as not visited 51 | boolean visited[] = new boolean[V]; 52 | for (int i = 0; i < V; i++) 53 | visited[i] = false; 54 | 55 | // Call the recursive helper function to store 56 | // Topological Sort starting from all vertices 57 | // one by one 58 | for (int i = 0; i < V; i++) 59 | if (visited[i] == false) 60 | topologicalSortUtil(i, visited, stack); 61 | 62 | // Print contents of stack 63 | while (stack.empty()==false) 64 | System.out.print(stack.pop() + " "); 65 | } 66 | 67 | // Driver method 68 | public static void main(String args[]) 69 | { 70 | // Create a graph given in the above diagram 71 | Graph g = new Graph(6); 72 | g.addEdge(5, 2); 73 | g.addEdge(5, 0); 74 | g.addEdge(4, 0); 75 | g.addEdge(4, 1); 76 | g.addEdge(2, 3); 77 | g.addEdge(3, 1); 78 | 79 | System.out.println("Following is a Topological " + 80 | "sort of the given graph"); 81 | g.topologicalSort(); 82 | } 83 | } -------------------------------------------------------------------------------- /java/Sorts/bubble_sort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by renu.yadav on 20/10/17. 3 | */ 4 | public class bubble_sort { 5 | /** 6 | * bubble sort , compares adjacent values and swap them if needed, 7 | * after every ith iteration ,ith biggest element would be in place 8 | * takes O(n^2) and an inplace algorithm with no extra space. 9 | * @param arr 10 | * @return 11 | */ 12 | // 13 | public int[] bubbleSort(int[] arr) { 14 | for (int i = 0; i < arr.length; i++) { 15 | for (int j = 0; j < arr.length - i - 1; j++) { 16 | if (arr[j + 1] < arr[j]) { 17 | // swap elements 18 | int temp = arr[j]; 19 | arr[j] = arr[j + 1]; 20 | arr[j + 1] = temp; 21 | } 22 | } 23 | } 24 | return arr; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /java/Sorts/insertion_sort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by renu.yadav on 20/10/17. 3 | */ 4 | public class insertion_sort { 5 | /** 6 | * insertion sort picks up the current element(i) and checks it against its previous element(j = i-1 until j>=0) and place it 7 | * takes O(n^2) and inplace algo with no extra space 8 | * @param arr 9 | * @return 10 | */ 11 | 12 | public static int[] insertionSort(int[] arr) { 13 | for (int i = 0; i < arr.length; i++) { 14 | int keyToBeInserted = arr[i]; 15 | int j = i - 1; 16 | while (j >= 0 && arr[j] > keyToBeInserted) { 17 | arr[j + 1] = arr[j]; 18 | } 19 | arr[j + 1] = keyToBeInserted; 20 | } 21 | return arr; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /java/Sorts/merge_sort.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Created by renu.yadav on 20/10/17. 4 | */ 5 | public class merge_sort { 6 | /** 7 | * Merge sort also works on divide and conquer , by dividing array in halves and then merging them back in order 8 | * Complexity: O(nlgn) in average , best and worst case 9 | * SpaceComplexity: because of merging in order , we need extra space O(n) (its not an in place algorithm) 10 | * 11 | * @param arr 12 | * @param low 13 | * @param high 14 | */ 15 | public static void mergeSort(int[] arr, int low, int high) { 16 | if (low >= high) 17 | return; 18 | int medium = low + (high - low) / 2; 19 | mergeSort(arr, low, medium); 20 | mergeSort(arr, medium + 1, high); 21 | merge(arr, low, medium, high); 22 | } 23 | 24 | public static void merge(int[] arr, int low, int medium, int high) { 25 | int s1 = medium - low + 1;// two sizes 26 | int s2 = high - medium; 27 | int[] a1 = new int[s1]; 28 | int[] a2 = new int[s2]; 29 | for (int i = 0; i < s1; i++) { 30 | a1[i] = arr[low + i]; 31 | } 32 | for (int i = 0; i < s2; i++) { 33 | a2[i] = arr[medium + i + 1]; 34 | } 35 | // now merge them in original array 36 | int i = 0; 37 | int j = 0; 38 | int k = low; 39 | // keep on merging them back in original , with correct order 40 | while (i < s1 && j < s2) { 41 | if (a1[i] <= a2[j]) { 42 | arr[k] = a1[i]; 43 | i++; 44 | } else { 45 | arr[k] = a2[j]; 46 | j++; 47 | } 48 | k++; 49 | } 50 | // place all remaining elements of s1 51 | while (i < s1) { 52 | arr[k] = a1[i]; 53 | i++; 54 | k++; 55 | 56 | } 57 | // place all remaining elements of s2 58 | while (j < s2) { 59 | arr[k] = a2[j]; 60 | j++; 61 | k++; 62 | } 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /java/Sorts/merge_sort_any.java: -------------------------------------------------------------------------------- 1 | import java.lang.reflect.Array; 2 | import java.util.ArrayList; 3 | 4 | /** 5 | * @author Casper Rysgaard 6 | */ 7 | public class MergeSort & Comparable> 8 | { 9 | /* 10 | * java class used for sorting any type of list 11 | */ 12 | 13 | public void sort(ArrayList arrayList) 14 | { 15 | mergeSortSplit(arrayList, 0, arrayList.size()-1); 16 | } 17 | 18 | private void mergeSortSplit(ArrayList listToSort, int start, int end) 19 | { 20 | if (start < end) 21 | { 22 | int middle = (start + end) / 2; 23 | mergeSortSplit(listToSort, start, middle); 24 | mergeSortSplit(listToSort, middle+1, end); 25 | merge(listToSort, start, middle, end); 26 | } 27 | } 28 | 29 | private void merge(ArrayList listToSort, int start, int middle, int end) 30 | { 31 | ArrayList A = new ArrayList(listToSort.subList(start, middle+1)); 32 | ArrayList B = new ArrayList(listToSort.subList(middle+1, end+1)); 33 | A.add(A.get(0).getMaxObject()); 34 | B.add(B.get(0).getMaxObject()); 35 | 36 | int i = 0; 37 | int j = 0; 38 | 39 | for (int k = start; k <= end; k++) 40 | { 41 | if (A.get(i).compareTo(B.get(j)) <= 0) 42 | { 43 | listToSort.set(k, A.get(i)); 44 | i++; 45 | } 46 | else 47 | { 48 | listToSort.set(k, B.get(j)); 49 | j++; 50 | } 51 | } 52 | } 53 | 54 | 55 | public void sort(T[] array) 56 | { 57 | /*ArrayList list = new ArrayList(Arrays.asList(array)); 58 | mergeSortSplit(list, 0, list.size()-1); 59 | array = list.toArray(array);*/ 60 | 61 | mergeSortSplitArray(array, 0, array.length-1); 62 | } 63 | 64 | private void mergeSortSplitArray(T[] listToSort, int start, int end) 65 | { 66 | if (start < end) 67 | { 68 | int middle = (start + end) / 2; 69 | mergeSortSplitArray(listToSort, start, middle); 70 | mergeSortSplitArray(listToSort, middle+1, end); 71 | mergeArray(listToSort, start, middle, end); 72 | } 73 | } 74 | 75 | private void mergeArray(T[] listToSort, int start, int middle, int end) 76 | { 77 | T[] A = (T[]) Array.newInstance(listToSort[0].getClass(),middle-start +2); 78 | T[] B = (T[]) Array.newInstance(listToSort[0].getClass(),end - middle +1); 79 | cloneArray(listToSort, A, start); 80 | cloneArray(listToSort, B, middle+1); 81 | 82 | int i = 0; 83 | int j = 0; 84 | 85 | for (int k = start; k <= end; k++) 86 | { 87 | if (A[i].compareTo(B[j]) <= 0) 88 | { 89 | listToSort[k] = A[i]; 90 | i++; 91 | } 92 | else 93 | { 94 | listToSort[k] = B[j]; 95 | j++; 96 | } 97 | } 98 | } 99 | 100 | private void cloneArray(T[] listIn, T[] cloneInto, int start) 101 | { 102 | for (int i = start; i < start+cloneInto.length-1; i++) 103 | { 104 | cloneInto[i - start] = listIn[i]; 105 | } 106 | 107 | cloneInto[cloneInto.length-1] = listIn[0].getMaxObject(); 108 | } 109 | } 110 | 111 | interface MaxValue 112 | { 113 | T getMaxObject(); 114 | } 115 | -------------------------------------------------------------------------------- /java/Sorts/quick_sort.java: -------------------------------------------------------------------------------- 1 | public class quick_sort { 2 | /** 3 | * quick sort works on divide and conquer technique , by chossing a pivot element 4 | * below code chooses last arr[n-1] element as pivot element and recursively placing all elements < pivot element on left 5 | * and all elements >pivot on right side of pivot , and thus placing pivot in correct place 6 | * Complexity: takes O(n^2) in worst case (array is already sorted ) ,and O(nlgn) in avg and best case 7 | * Space complexity ; No extra space required 8 | * @param arr 9 | * @param low 10 | * @param high 11 | */ 12 | 13 | public static void quickSort(int[] arr, int low, int high) { 14 | if (low >= high) 15 | return; 16 | int pivot = partition(arr, low, high); 17 | quickSort(arr, low, pivot - 1); 18 | quickSort(arr, pivot + 1, high); 19 | 20 | } 21 | 22 | public static int partition(int[] arr, int low, int high) { 23 | int pivot = arr[high]; 24 | int i = low - 1; 25 | int j = low; 26 | while (j < high) { 27 | if (arr[j] <= pivot) { 28 | i++; 29 | // swap elements 30 | int temp = arr[i]; 31 | arr[i] = arr[j]; 32 | arr[j] = temp; 33 | } 34 | j++; 35 | } 36 | // swap arr[i+1] with arr[high] 37 | int temp = arr[high]; 38 | arr[high] = arr[i + 1]; 39 | arr[i + 1] = temp; 40 | return i + 1; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /java/Sorts/selection_sort.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Created by renu.yadav on 20/10/17. 3 | */ 4 | public class selection_sort { 5 | /** 6 | * selection sort in iteration , picks up the ith min element and keep it in place 7 | * so after every ith iteration ith minimum element is in place 8 | * takes O(n^2) 9 | * @param arr 10 | * @return 11 | */ 12 | public static int[] selectionSort(int[] arr) { 13 | for (int i = 0; i < arr.length; i++) { 14 | int minIndex = i; 15 | int minElement = arr[minIndex]; 16 | for (int j = i + 1; j < arr.length; j++) { 17 | if (arr[j] < minElement) { 18 | minIndex = j; 19 | } 20 | } 21 | // swap , arr[i] with minElement 22 | int temp = arr[i]; 23 | arr[i] = arr[minIndex]; 24 | arr[minIndex] = temp; 25 | } 26 | return arr; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /javascript/Data_structures/queue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Data Structures with JavaScript :: Queue 3 | * 4 | * A linear data structure. 5 | * 6 | * FIFO (First In First Out) 7 | * 8 | * Operations of a Queue: 9 | * - enqueue: which adds an element to the collection 10 | * - dequeue: which removes the first added element that was not yet removed 11 | * 12 | * https://en.wikipedia.org/wiki/Queue_(abstract_data_type) 13 | */ 14 | 15 | function Queue() { 16 | this.items = []; // Container for storing data 17 | this.maxsize = 1024; // Maximum number of elements 18 | } 19 | 20 | /** 21 | * Add an element to the collection 22 | */ 23 | Queue.prototype.enqueue = function(item) { 24 | if (this.items.length >= this.maxsize) { 25 | // overflow error 26 | return undefined; 27 | } 28 | 29 | this.items.push(item); 30 | } 31 | 32 | /** 33 | * Remove an element from the collection 34 | */ 35 | Queue.prototype.dequeue = function() { 36 | if (this.items.length <= 0) { 37 | // underflow error 38 | return undefined; 39 | } 40 | 41 | return this.items.shift(); 42 | } 43 | 44 | /** 45 | * Observes the first element without removing it from the queue 46 | */ 47 | Queue.prototype.peek = function() { 48 | if (this.items.length == 0) { 49 | // is empty 50 | return undefined; 51 | } 52 | 53 | return this.items[0] 54 | } 55 | 56 | /** 57 | * Returns the number of elements in the queue 58 | */ 59 | Queue.prototype.size = function() { 60 | return this.items.length; 61 | } 62 | 63 | /** 64 | * Example 65 | */ 66 | 67 | var queue = new Queue(); 68 | 69 | queue.enqueue('a'); 70 | console.log(queue.peek()); 71 | queue.enqueue('b'); 72 | console.log(queue.peek()); 73 | 74 | console.log(queue.dequeue()); 75 | console.log(queue.peek()); 76 | 77 | console.log(queue.size()); 78 | console.log(queue.peek()); 79 | -------------------------------------------------------------------------------- /javascript/Search/binary_search.js: -------------------------------------------------------------------------------- 1 | // A recursive binary search algorithm. 2 | // It returns location of x in a given array arr[l..r] is present, otherwise -1 3 | const binarySearch = (arr, l, r, x) => 4 | { 5 | if (r >= l) 6 | { 7 | const mid = Math.floor(l + (r - l) / 2); 8 | 9 | // If the element is present at the middle itself 10 | if (arr[mid] == x) return mid; 11 | 12 | // If element is smaller than mid, then it can only be present 13 | // in left subarray 14 | if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); 15 | 16 | // Else the element can only be present in right subarray 17 | return binarySearch(arr, mid + 1, r, x); 18 | } 19 | 20 | // We reach here when element is not present in array 21 | return -1; 22 | } 23 | 24 | 25 | const search = (arr, x) => { 26 | return binarySearch(arr, 0, arr.length, x); 27 | } 28 | 29 | const arr = [2, 3, 4, 10, 40]; 30 | const x = 3; 31 | const result = search(arr, x); 32 | (result == -1) ? console.log("Element is not present in array") 33 | : console.log("Element is present at index %d \n", result); -------------------------------------------------------------------------------- /javascript/Sorting_algorithms/bubble_sort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(items) 2 | { 3 | var length = items.length; 4 | for (var i = 0; i < length; i++) 5 | { 6 | for (var j = 0; j < (length - i - 1); j++) 7 | { 8 | if(items[j] > items[j+1]) 9 | { 10 | var tmp = items[j]; 11 | items[j] = items[j+1]; 12 | items[j+1] = tmp; 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /javascript/Sorting_algorithms/insertion_sort.js: -------------------------------------------------------------------------------- 1 | // the array to sort 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | function insertionSort(array) { 5 | for(var i = 0; i < array.length; i++) { 6 | var temp = array[i]; 7 | var j = i - 1; 8 | while (j >= 0 && array[j] > temp) { 9 | array[j + 1] = array[j]; 10 | j--; 11 | } 12 | array[j + 1] = temp; 13 | } 14 | return array; 15 | } 16 | 17 | console.log(insertionSort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 18 | -------------------------------------------------------------------------------- /javascript/Sorting_algorithms/merge_sort.js: -------------------------------------------------------------------------------- 1 | // ++++The array to sort++++ 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | // the top-down implementation 5 | function mergeSortTopDown(array) { 6 | if(array.length < 2) { 7 | return array; 8 | } 9 | 10 | var middle = Math.floor(array.length / 2); 11 | var left = array.slice(0, middle); 12 | var right = array.slice(middle); 13 | 14 | return mergeTopDown(mergeSortTopDown(left), mergeSortTopDown(right)); 15 | } 16 | function mergeTopDown(left, right) { 17 | var array = []; 18 | 19 | while(left.length && right.length) { 20 | if(left[0] < right[0]) { 21 | array.push(left.shift()); 22 | } else { 23 | array.push(right.shift()); 24 | } 25 | } 26 | return array.concat(left.slice()).concat(right.slice()); 27 | } 28 | 29 | console.log(mergeSortTopDown(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 30 | 31 | // the bottom-up implementation 32 | function mergeSortBottomUp(array) { 33 | var step = 1; 34 | while (step < array.length) { 35 | var left = 0; 36 | while (left + step < array.length) { 37 | mergeBottomUp(array, left, step); 38 | left += step * 2; 39 | } 40 | step *= 2; 41 | } 42 | return array; 43 | } 44 | function mergeBottomUp(array, left, step) { 45 | var right = left + step; 46 | var end = Math.min(left + step * 2 - 1, array.length - 1); 47 | var leftMoving = left; 48 | var rightMoving = right; 49 | var temp = []; 50 | 51 | for (var i = left; i <= end; i++) { 52 | if ((array[leftMoving] <= array[rightMoving] || rightMoving > end) && 53 | leftMoving < right) { 54 | temp[i] = array[leftMoving]; 55 | leftMoving++; 56 | } else { 57 | temp[i] = array[rightMoving]; 58 | rightMoving++; 59 | } 60 | } 61 | 62 | for (var j = left; j <= end; j++) { 63 | array[j] = temp[j]; 64 | } 65 | } 66 | 67 | console.log(mergeSortBottomUp(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 68 | -------------------------------------------------------------------------------- /javascript/Sorting_algorithms/quicksort.js: -------------------------------------------------------------------------------- 1 | // here the array to sort++ 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | // the basic implementation (take pivot as the first element of the array) 5 | function quicksortBasic(array) { 6 | if(array.length < 2) { 7 | return array; 8 | } 9 | 10 | var pivot = array[0]; 11 | var lesser = []; 12 | var greater = []; 13 | 14 | for(var i = 1; i < array.length; i++) { 15 | if(array[i] < pivot) { 16 | lesser.push(array[i]); 17 | } else { 18 | greater.push(array[i]); 19 | } 20 | } 21 | 22 | return quicksortBasic(lesser).concat(pivot, quicksortBasic(greater)); 23 | } 24 | 25 | console.log(quicksortBasic(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 26 | 27 | // swap function helper 28 | function swap(array, i, j) { 29 | var temp = array[i]; 30 | array[i] = array[j]; 31 | array[j] = temp; 32 | } 33 | 34 | // classic implementation (with Hoare or Lomuto partition scheme, you can comment either one method or the other to see the difference) 35 | function quicksort(array, left, right) { 36 | left = left || 0; 37 | right = right || array.length - 1; 38 | 39 | // var pivot = partitionLomuto(array, left, right); // you can play with both partition 40 | var pivot = partitionHoare(array, left, right); // you can play with both partition 41 | 42 | if(left < pivot - 1) { 43 | quicksort(array, left, pivot - 1); 44 | } 45 | if(right > pivot) { 46 | quicksort(array, pivot, right); 47 | } 48 | return array; 49 | } 50 | // Lomuto partition scheme, it is less efficient than the Hoare partition scheme 51 | function partitionLomuto(array, left, right) { 52 | var pivot = right; 53 | var i = left; 54 | 55 | for(var j = left; j < right; j++) { 56 | if(array[j] <= array[pivot]) { 57 | swap(array, i, j); 58 | i = i + 1; 59 | } 60 | } 61 | swap(array, i, j); 62 | return i; 63 | } 64 | // Hoare partition scheme, it is more efficient than the Lomuto partition scheme because it does three times fewer swaps on average 65 | function partitionHoare(array, left, right) { 66 | var pivot = Math.floor((left + right) / 2 ); 67 | 68 | while(left <= right) { 69 | while(array[left] < array[pivot]) { 70 | left++; 71 | } 72 | while(array[right] > array[pivot]) { 73 | right--; 74 | } 75 | if(left <= right) { 76 | swap(array, left, right); 77 | left++; 78 | right--; 79 | } 80 | } 81 | return left; 82 | } 83 | 84 | console.log(quicksort(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 85 | -------------------------------------------------------------------------------- /javascript/Sorting_algorithms/selection_sort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr) 2 | { 3 | var minIdx, temp, 4 | len = arr.length; 5 | for(var i = 0; i < len; i++) 6 | { 7 | minIdx = i; 8 | for(var j = i+1; j= gap && array[j - gap] > temp; j -= gap) { 13 | array[j] = array[j - gap]; 14 | } 15 | array[j] = temp; 16 | } 17 | } 18 | return array; 19 | } 20 | 21 | console.log(shellsort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 22 | -------------------------------------------------------------------------------- /javascript/array.js: -------------------------------------------------------------------------------- 1 | 2 | //++++ Implement array data structure in javascript++++ 3 | 4 | 5 | function this_array() { 6 | this.array = []; 7 | } 8 | 9 | this_array.prototype.add = function(data) { 10 | this.array.push(data); 11 | }; 12 | this_array.prototype.remove = function(data) { 13 | this.array = this.array.filter(function(current) { 14 | return current !== data; 15 | }); 16 | }; 17 | this_array.prototype.search = function(data) { 18 | var foundIndex = this.array.indexOf(data); 19 | if(~foundIndex) { 20 | return foundIndex; 21 | } 22 | 23 | return null; 24 | }; 25 | this_array.prototype.getAtIndex = function(index) { 26 | return this.array[index]; 27 | }; 28 | this_array.prototype.length = function() { 29 | return this.array.length; 30 | }; 31 | this_array.prototype.print = function() { 32 | console.log(this.array.join(' ')); 33 | }; 34 | 35 | var array = new this_array(); 36 | array.add(1); 37 | array.add(2); 38 | array.add(3); 39 | array.add(4); 40 | array.print(); // => 1 2 3 4 41 | console.log('search 3 gives index 2:', array.search(3)); // => 2 42 | console.log('getAtIndex 2 gives 3:', array.getAtIndex(2)); // => 3 43 | console.log('length is 4:', array.length()); // => 4 44 | array.remove(3); 45 | array.print(); // => 1 2 4 46 | array.add(5); 47 | array.add(5); 48 | array.print(); // => 1 2 4 5 5 49 | array.remove(5); 50 | array.print(); // => 1 2 4 51 | -------------------------------------------------------------------------------- /javascript/binary_search.js: -------------------------------------------------------------------------------- 1 | // A recursive binary search algorithm. 2 | // It returns location of x in a given array arr[l..r] is present, otherwise -1 3 | const binarySearch = (arr, l, r, x) => 4 | { 5 | if (r >= l) 6 | { 7 | const mid = Math.floor(l + (r - l) / 2); 8 | 9 | // If the element is present at the middle itself 10 | if (arr[mid] == x) return mid; 11 | 12 | // If element is smaller than mid, then it can only be present 13 | // in left subarray 14 | if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); 15 | 16 | // Else the element can only be present in right subarray 17 | return binarySearch(arr, mid + 1, r, x); 18 | } 19 | 20 | // We reach here when element is not present in array 21 | return -1; 22 | } 23 | 24 | 25 | const search = (arr, x) => { 26 | return binarySearch(arr, 0, arr.length, x); 27 | } 28 | 29 | const arr = [2, 3, 4, 10, 40]; 30 | const x = 3; 31 | const result = search(arr, x); 32 | (result == -1) ? console.log("Element is not present in array") 33 | : console.log("Element is present at index %d \n", result); -------------------------------------------------------------------------------- /javascript/bubble_sort.js: -------------------------------------------------------------------------------- 1 | function bubbleSort(items) 2 | { 3 | var length = items.length; 4 | for (var i = 0; i < length; i++) 5 | { 6 | for (var j = 0; j < (length - i - 1); j++) 7 | { 8 | if(items[j] > items[j+1]) 9 | { 10 | var tmp = items[j]; 11 | items[j] = items[j+1]; 12 | items[j+1] = tmp; 13 | } 14 | } 15 | } 16 | } -------------------------------------------------------------------------------- /javascript/greatest_common_divisor.js: -------------------------------------------------------------------------------- 1 | function greatestCommonDivisor(a, b){ 2 | var divisor = 2, 3 | greatestDivisor = 1; 4 | 5 | //if u pass a -ve number this will not work. fix it dude!! 6 | if (a < 2 || b < 2) 7 | return 1; 8 | 9 | while(a >= divisor && b >= divisor){ 10 | if(a %divisor == 0 && b% divisor ==0){ 11 | greatestDivisor = divisor; 12 | } 13 | divisor++; 14 | } 15 | return greatestDivisor; 16 | } 17 | 18 | // > greatestCommonDivisor(14, 21); 19 | // =7 20 | // > greatestCommonDivisor(69, 169); 21 | // = 1 22 | -------------------------------------------------------------------------------- /javascript/insertion_sort.js: -------------------------------------------------------------------------------- 1 | // the array to sort 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | function insertionSort(array) { 5 | for(var i = 0; i < array.length; i++) { 6 | var temp = array[i]; 7 | var j = i - 1; 8 | while (j >= 0 && array[j] > temp) { 9 | array[j + 1] = array[j]; 10 | j--; 11 | } 12 | array[j + 1] = temp; 13 | } 14 | return array; 15 | } 16 | 17 | console.log(insertionSort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 18 | -------------------------------------------------------------------------------- /javascript/merge_sort.js: -------------------------------------------------------------------------------- 1 | // ++++The array to sort++++ 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | // the top-down implementation 5 | function mergeSortTopDown(array) { 6 | if(array.length < 2) { 7 | return array; 8 | } 9 | 10 | var middle = Math.floor(array.length / 2); 11 | var left = array.slice(0, middle); 12 | var right = array.slice(middle); 13 | 14 | return mergeTopDown(mergeSortTopDown(left), mergeSortTopDown(right)); 15 | } 16 | function mergeTopDown(left, right) { 17 | var array = []; 18 | 19 | while(left.length && right.length) { 20 | if(left[0] < right[0]) { 21 | array.push(left.shift()); 22 | } else { 23 | array.push(right.shift()); 24 | } 25 | } 26 | return array.concat(left.slice()).concat(right.slice()); 27 | } 28 | 29 | console.log(mergeSortTopDown(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 30 | 31 | // the bottom-up implementation 32 | function mergeSortBottomUp(array) { 33 | var step = 1; 34 | while (step < array.length) { 35 | var left = 0; 36 | while (left + step < array.length) { 37 | mergeBottomUp(array, left, step); 38 | left += step * 2; 39 | } 40 | step *= 2; 41 | } 42 | return array; 43 | } 44 | function mergeBottomUp(array, left, step) { 45 | var right = left + step; 46 | var end = Math.min(left + step * 2 - 1, array.length - 1); 47 | var leftMoving = left; 48 | var rightMoving = right; 49 | var temp = []; 50 | 51 | for (var i = left; i <= end; i++) { 52 | if ((array[leftMoving] <= array[rightMoving] || rightMoving > end) && 53 | leftMoving < right) { 54 | temp[i] = array[leftMoving]; 55 | leftMoving++; 56 | } else { 57 | temp[i] = array[rightMoving]; 58 | rightMoving++; 59 | } 60 | } 61 | 62 | for (var j = left; j <= end; j++) { 63 | array[j] = temp[j]; 64 | } 65 | } 66 | 67 | console.log(mergeSortBottomUp(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 68 | -------------------------------------------------------------------------------- /javascript/queue.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Data Structures with JavaScript :: Queue 3 | * 4 | * A linear data structure. 5 | * 6 | * FIFO (First In First Out) 7 | * 8 | * Operations of a Queue: 9 | * - enqueue: which adds an element to the collection 10 | * - dequeue: which removes the first added element that was not yet removed 11 | * 12 | * https://en.wikipedia.org/wiki/Queue_(abstract_data_type) 13 | */ 14 | 15 | function Queue() { 16 | this.items = []; // Container for storing data 17 | this.maxsize = 1024; // Maximum number of elements 18 | } 19 | 20 | /** 21 | * Add an element to the collection 22 | */ 23 | Queue.prototype.enqueue = function(item) { 24 | if (this.items.length >= this.maxsize) { 25 | // overflow error 26 | return undefined; 27 | } 28 | 29 | this.items.push(item); 30 | } 31 | 32 | /** 33 | * Remove an element from the collection 34 | */ 35 | Queue.prototype.dequeue = function() { 36 | if (this.items.length <= 0) { 37 | // underflow error 38 | return undefined; 39 | } 40 | 41 | return this.items.shift(); 42 | } 43 | 44 | /** 45 | * Observes the first element without removing it from the queue 46 | */ 47 | Queue.prototype.peek = function() { 48 | if (this.items.length == 0) { 49 | // is empty 50 | return undefined; 51 | } 52 | 53 | return this.items[0] 54 | } 55 | 56 | /** 57 | * Returns the number of elements in the queue 58 | */ 59 | Queue.prototype.size = function() { 60 | return this.items.length; 61 | } 62 | 63 | /** 64 | * Example 65 | */ 66 | 67 | var queue = new Queue(); 68 | 69 | queue.enqueue('a'); 70 | console.log(queue.peek()); 71 | queue.enqueue('b'); 72 | console.log(queue.peek()); 73 | 74 | console.log(queue.dequeue()); 75 | console.log(queue.peek()); 76 | 77 | console.log(queue.size()); 78 | console.log(queue.peek()); 79 | -------------------------------------------------------------------------------- /javascript/quicksort.js: -------------------------------------------------------------------------------- 1 | // here the array to sort++ 2 | var array = [9, 2, 5, 6, 4, 3, 7, 10, 1, 8]; 3 | 4 | // the basic implementation (take pivot as the first element of the array) 5 | function quicksortBasic(array) { 6 | if(array.length < 2) { 7 | return array; 8 | } 9 | 10 | var pivot = array[0]; 11 | var lesser = []; 12 | var greater = []; 13 | 14 | for(var i = 1; i < array.length; i++) { 15 | if(array[i] < pivot) { 16 | lesser.push(array[i]); 17 | } else { 18 | greater.push(array[i]); 19 | } 20 | } 21 | 22 | return quicksortBasic(lesser).concat(pivot, quicksortBasic(greater)); 23 | } 24 | 25 | console.log(quicksortBasic(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 26 | 27 | // swap function helper 28 | function swap(array, i, j) { 29 | var temp = array[i]; 30 | array[i] = array[j]; 31 | array[j] = temp; 32 | } 33 | 34 | // classic implementation (with Hoare or Lomuto partition scheme, you can comment either one method or the other to see the difference) 35 | function quicksort(array, left, right) { 36 | left = left || 0; 37 | right = right || array.length - 1; 38 | 39 | // var pivot = partitionLomuto(array, left, right); // you can play with both partition 40 | var pivot = partitionHoare(array, left, right); // you can play with both partition 41 | 42 | if(left < pivot - 1) { 43 | quicksort(array, left, pivot - 1); 44 | } 45 | if(right > pivot) { 46 | quicksort(array, pivot, right); 47 | } 48 | return array; 49 | } 50 | // Lomuto partition scheme, it is less efficient than the Hoare partition scheme 51 | function partitionLomuto(array, left, right) { 52 | var pivot = right; 53 | var i = left; 54 | 55 | for(var j = left; j < right; j++) { 56 | if(array[j] <= array[pivot]) { 57 | swap(array, i, j); 58 | i = i + 1; 59 | } 60 | } 61 | swap(array, i, j); 62 | return i; 63 | } 64 | // Hoare partition scheme, it is more efficient than the Lomuto partition scheme because it does three times fewer swaps on average 65 | function partitionHoare(array, left, right) { 66 | var pivot = Math.floor((left + right) / 2 ); 67 | 68 | while(left <= right) { 69 | while(array[left] < array[pivot]) { 70 | left++; 71 | } 72 | while(array[right] > array[pivot]) { 73 | right--; 74 | } 75 | if(left <= right) { 76 | swap(array, left, right); 77 | left++; 78 | right--; 79 | } 80 | } 81 | return left; 82 | } 83 | 84 | console.log(quicksort(array.slice())); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 85 | -------------------------------------------------------------------------------- /javascript/selection_sort.js: -------------------------------------------------------------------------------- 1 | function selectionSort(arr) 2 | { 3 | var minIdx, temp, 4 | len = arr.length; 5 | for(var i = 0; i < len; i++) 6 | { 7 | minIdx = i; 8 | for(var j = i+1; j= gap && array[j - gap] > temp; j -= gap) { 13 | array[j] = array[j - gap]; 14 | } 15 | array[j] = temp; 16 | } 17 | } 18 | return array; 19 | } 20 | 21 | console.log(shellsort(array)); // => [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] 22 | -------------------------------------------------------------------------------- /kotlin/Search/binarysearch.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) = 2 | println(binarySearch(intArrayOf(1, 2, 3, 4 ,5), 2)) 3 | 4 | fun binarySearch(a: IntArray, b: Int): Int { 5 | var lower = 0 6 | var higher = a.size 7 | var mid: Int 8 | while (lower <= higher) { 9 | mid = lower + (higher - lower) / 2 10 | when { 11 | a[mid] == b -> return mid 12 | a[mid] < b -> lower = mid + 1 13 | a[mid] > b -> higher = mid - 1 14 | } 15 | } 16 | return -1 17 | } 18 | -------------------------------------------------------------------------------- /kotlin/Search/linearsearch.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) = 2 | println(linearSearch(intArrayOf(1, 2, 3, 4 ,5), 2)) 3 | 4 | 5 | fun linearSearch(arr: IntArray, item: Int): Int = 6 | (0 until arr.size).firstOrNull { arr[it] == item } ?: -1 7 | -------------------------------------------------------------------------------- /kotlin/fibonacci.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | val fibonacci = Fibonacci() 3 | println(fibonacci.execute(5)) 4 | } 5 | 6 | class Fibonacci { 7 | 8 | fun execute(n: Int) : List { 9 | return (1..n).map { fib(it) } 10 | } 11 | 12 | private fun fib(n: Int) : Int = when (n) { 13 | 1 -> n 14 | else -> fib(n - 1) + fib(n - 2) 15 | } 16 | } -------------------------------------------------------------------------------- /php/Search/binary_search.php: -------------------------------------------------------------------------------- 1 | = $bottom) { 12 | 13 | $middle = floor(($top + $bottom) / 2); 14 | if ($array[$middle] < $value) $bottom = $middle + 1; 15 | elseif ($array[$middle] > $value) $top = $middle - 1; 16 | else return true; 17 | 18 | } 19 | 20 | return false; 21 | } 22 | 23 | } -------------------------------------------------------------------------------- /php/Sorting_algorithm/insertion_sort.php: -------------------------------------------------------------------------------- 1 | /**Function for sorting an array with insertion sort algorithm 2 | */ 3 | 4 | =0 && $this_array[$j] > $val){ 12 | $this_array[$j+1] = $this_array[$j]; 13 | $j--; 14 | } 15 | $this_array[$j+1] = $val; 16 | } 17 | return $this_array; 18 | } 19 | $test_array = array(3, 0, 2, 5, -1, 4, 1); 20 | echo "Original Array :\n"; 21 | echo implode(', ',$chk_array ); 22 | echo "\nSorted Array :\n"; 23 | print_r(insertion_Sort($chk_array)); 24 | ?> 25 | 26 | 27 | /** +++++++++++ Sample Output ++++++++++++ 28 | * 29 | * Original Array : 30 | * 3, 0, 2, 5, -1, 4, 1 31 | * Sorted Array : 32 | * Array 33 | * ( 34 | * [0] => -1 35 | * [1] => 0 36 | * [2] => 1 37 | * [3] => 2 38 | * [4] => 3 39 | * [5] => 4 40 | * [6] => 5 41 | * ) 42 | */ 43 | 44 | 45 | 46 | -------------------------------------------------------------------------------- /python/Backtracking/binary_string.py: -------------------------------------------------------------------------------- 1 | # To print all the binary string for a given 'n' value 2 | 3 | def binary(n,bi): 4 | 5 | if (n == -1): 6 | print ''.join(bi) 7 | return 8 | else: 9 | bi[n] = str(0) 10 | binary(n-1, bi) 11 | bi[n] = str(1) 12 | binary(n-1, bi) 13 | 14 | 15 | n = input() 16 | bi = [] 17 | 18 | # Defining a list of size n with dummy values 19 | for i in range(n): 20 | bi.append(-1) 21 | 22 | binary(n-1, bi) 23 | -------------------------------------------------------------------------------- /python/Backtracking/coin_denom.py: -------------------------------------------------------------------------------- 1 | """ 2 | Coin denomination problem - Topdown Memoization Approach (Dynamic Programming) 3 | Example: Given the coins with denomination [1,2,3]. Assume that there are infinite number of coins. Find the minimum number of coins to get the value 'x'. 4 | """ 5 | 6 | # maxint returns maximum integer value supported python 2.7 7 | from sys import maxint 8 | 9 | 10 | def coin_denom(coins,dictionary,remain): 11 | 12 | if remain == 0: 13 | return 0 14 | elif remain < 0: 15 | return -1 16 | 17 | if remain in dictionary: 18 | return dictionary[remain] 19 | 20 | # In Python 2.7, maximum integer value is 2147483647 21 | min_val = maxint 22 | 23 | for i in coins: 24 | temp = 1 + coin_denom(coins,dictionary,remain-i) 25 | if temp < min_val and temp != 0: 26 | min_val = temp 27 | 28 | if remain not in dictionary: 29 | dictionary[remain] = min_val 30 | 31 | return min_val 32 | 33 | ### Testcases ### 34 | #print coin_denom([1,2,3,4], {}, 7) 35 | -------------------------------------------------------------------------------- /python/Backtracking/n_queen.py: -------------------------------------------------------------------------------- 1 | """ 2 | N-Queen problem 3 | Time Complexiy is exponential (it is based on the size of the table) 4 | Space Complexiy - O(n) 5 | """ 6 | 7 | class N_Queen(object): 8 | 9 | def possibility(self,row,column,q_row,q_column): 10 | left_diagonal = q_row + q_column 11 | right_diagonal = q_row - q_column 12 | 13 | if q_row == row: 14 | return False 15 | elif q_column == column: 16 | return False 17 | elif row + column == left_diagonal: 18 | return False 19 | elif row - column == right_diagonal: 20 | return False 21 | else: 22 | return True 23 | 24 | 25 | def queen(self,n,row,previous_queen,result): 26 | if row == n: 27 | print result 28 | return True 29 | 30 | # Iterating the columns 31 | for j in range(n): 32 | valid = True 33 | for q in range(len(previous_queen)): 34 | if(not(self.possibility(row,j,previous_queen[q][0],previous_queen[q][1]))): 35 | valid = False 36 | break 37 | 38 | if(valid): 39 | previous_queen.append([row,j]) 40 | result[row][j] = 'Queen' 41 | if(self.queen(n,row+1,previous_queen,result)): 42 | return True 43 | else: 44 | previous_queen.remove([row,j]) 45 | result[row][j] = 0 46 | 47 | return False 48 | 49 | 50 | def solveNQueens(self, n): 51 | 52 | result = [] 53 | for i in range(n): 54 | result.append([]) 55 | for j in range(n): 56 | # Void is zero - 0 57 | result[i].append(0) 58 | previous_queen = [] 59 | self.queen(n,0,previous_queen,result) 60 | 61 | 62 | obj = N_Queen() 63 | obj.solveNQueens(4) 64 | -------------------------------------------------------------------------------- /python/Backtracking/string_permutations.py: -------------------------------------------------------------------------------- 1 | """ 2 | Print all the string permutations using backtracking method. 3 | """ 4 | def permutations(string,index,size): 5 | 6 | if index == size: 7 | print ''.join(string) 8 | return 9 | 10 | for i in range(index,size): 11 | string[i], string[index] = string[index], string[i] 12 | permutations(string,index+1,size) 13 | string[i], string[index] = string[index], string[i] 14 | 15 | 16 | string = raw_input() 17 | string = list(string) 18 | size = len(string) 19 | print permutations(string,0,size) 20 | -------------------------------------------------------------------------------- /python/Data_structures/BinarySearchTree.py: -------------------------------------------------------------------------------- 1 | 2 | class Node: 3 | 4 | def __init__(self, label): 5 | self.label = label 6 | self.left = None 7 | self.right = None 8 | 9 | def getLabel(self): 10 | return self.label 11 | 12 | def setLabel(self, label): 13 | self.label = label 14 | 15 | def getLeft(self): 16 | return self.left 17 | 18 | def setLeft(self, left): 19 | self.left = left 20 | 21 | def getRight(self): 22 | return self.right 23 | 24 | def setRight(self, right): 25 | self.right = right 26 | 27 | 28 | class BinarySearchTree: 29 | 30 | def __init__(self): 31 | self.root = None 32 | 33 | def insert(self, label): 34 | 35 | # Create a new Node 36 | 37 | node = Node(label) 38 | 39 | if self.empty(): 40 | self.root = node 41 | else: 42 | parent_node = None 43 | cur_node = self.root 44 | 45 | while True: 46 | if cur_node is not None: 47 | 48 | parent_node = cur_node 49 | 50 | if node.getLabel() < cur_node.getLabel(): 51 | cur_node = cur_node.getLeft() 52 | else: 53 | cur_node = cur_node.getRight() 54 | else: 55 | if node.getLabel() < parent_node.getLabel(): 56 | parent_node.setLeft(node) 57 | else: 58 | parent_node.setRight(node) 59 | break 60 | 61 | def empty(self): 62 | if self.root is None: 63 | return True 64 | return False 65 | 66 | def preOrder(self, cur_node): 67 | if cur_node is not None: 68 | print(cur_node.getLabel(), end=" ") 69 | 70 | self.preOrder(cur_node.getLeft()) 71 | self.preOrder(cur_node.getRight()) 72 | 73 | def postOrder(self, cur_node): 74 | if cur_node is not None: 75 | self.postOrder(cur_node.getLeft()) 76 | self.postOrder(cur_node.getRight()) 77 | print(cur_node.getLabel(), end=" ") 78 | 79 | def inOrder(self, cur_node): 80 | if cur_node is not None: 81 | self.inOrder(cur_node.getLeft()) 82 | print(cur_node.getLabel(), end =" ") 83 | self.inOrder(cur_node.getRight()) 84 | 85 | def getRoot(self): 86 | return self.root 87 | 88 | 89 | 90 | t = BinarySearchTree() 91 | t.insert(4) 92 | t.insert(2) 93 | t.insert(1) 94 | t.insert(3) 95 | t.insert(6) 96 | t.insert(5) 97 | t.insert(7) 98 | 99 | 100 | t.preOrder(t.getRoot()) 101 | print("\n") 102 | t.inOrder(t.getRoot()) 103 | print("\n") 104 | t.postOrder(t.getRoot()) 105 | print("\n") 106 | -------------------------------------------------------------------------------- /python/Data_structures/BreadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | 2 | class Graph(): 3 | def __init__(self): 4 | self.vertex = {} 5 | 6 | # for printing the Graph vertexes 7 | def printGraph(self): 8 | for i in self.vertex.keys(): 9 | print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) 10 | 11 | # for adding the edge beween two vertexes 12 | def addEdge(self, fromVertex, toVertex): 13 | # check if vertex is already present, 14 | if fromVertex in self.vertex.keys(): 15 | self.vertex[fromVertex].append(toVertex) 16 | else: 17 | # else make a new vertex 18 | self.vertex[fromVertex] = [toVertex] 19 | 20 | def BFS(self, startVertex): 21 | # Take a list for stoting already visited vertexes 22 | visited = [False] * len(self.vertex) 23 | 24 | # create a list to store all the vertexes for BFS 25 | queue = [] 26 | 27 | # mark the source node as visited and enqueue it 28 | visited[startVertex] = True 29 | queue.append(startVertex) 30 | 31 | while queue: 32 | startVertex = queue.pop(0) 33 | print(startVertex, end = ' ') 34 | 35 | # mark all adjacent nodes as visited and print them 36 | for i in self.vertex[startVertex]: 37 | if visited[i] == False: 38 | queue.append(i) 39 | visited[i] = True 40 | 41 | if __name__ == '__main__': 42 | g = Graph() 43 | g.addEdge(0, 1) 44 | g.addEdge(0, 2) 45 | g.addEdge(1, 2) 46 | g.addEdge(2, 0) 47 | g.addEdge(2, 3) 48 | g.addEdge(3, 3) 49 | 50 | g.printGraph() 51 | print('BFS:') 52 | g.BFS(2) 53 | 54 | # OUTPUT: 55 | # 0 -> 1 -> 2 56 | # 1 -> 2 57 | # 2 -> 0 -> 3 58 | # 3 -> 3 59 | # BFS: 60 | # 2 0 3 1 61 | -------------------------------------------------------------------------------- /python/Data_structures/Depth-First _Search_Recursive_Function.py: -------------------------------------------------------------------------------- 1 | def dfs_recursive(graph, vertex, path=[]): 2 | path += [vertex] 3 | 4 | for neighbor in graph[vertex]: 5 | if neighbor not in path: 6 | path = dfs_recursive(graph, neighbor, path) 7 | 8 | return path 9 | 10 | 11 | adjacency_matrix = {1: [2, 3], 2: [4, 5], 12 | 3: [5], 4: [6], 5: [6], 13 | 6: [7], 7: []} 14 | 15 | print(dfs_recursive(adjacency_matrix, 1)) 16 | # [1, 2, 4, 6, 7, 5, 3] 17 | -------------------------------------------------------------------------------- /python/Data_structures/kruskal.py: -------------------------------------------------------------------------------- 1 | #kruskal's algorithm for minimum spanning tree 2 | parent = dict() 3 | rank = dict() 4 | 5 | def make_set(vertice): 6 | parent[vertice] = vertice 7 | rank[vertice] = 0 8 | 9 | def find(vertice): 10 | if parent[vertice] != vertice: 11 | parent[vertice] = find(parent[vertice]) 12 | return parent[vertice] 13 | 14 | def union(vertice1, vertice2): 15 | root1 = find(vertice1) 16 | root2 = find(vertice2) 17 | if root1 != root2: 18 | if rank[root1] > rank[root2]: 19 | parent[root2] = root1 20 | else: 21 | parent[root1] = root2 22 | if rank[root1] == rank[root2]: rank[root2] += 1 23 | 24 | def kruskal(graph): 25 | for vertice in graph['vertices']: 26 | make_set(vertice) 27 | 28 | minimum_spanning_tree = set() 29 | edges = list(graph['edges']) 30 | edges.sort() 31 | for edge in edges: 32 | weight, vertice1, vertice2 = edge 33 | if find(vertice1) != find(vertice2): 34 | union(vertice1, vertice2) 35 | minimum_spanning_tree.add(edge) 36 | return minimum_spanning_tree 37 | -------------------------------------------------------------------------------- /python/Data_structures/stack.py: -------------------------------------------------------------------------------- 1 | class Stack: 2 | 3 | def __init__(self): 4 | self._data = [] 5 | 6 | def push(self, x): 7 | self._data.append(x) 8 | 9 | def pop(self): 10 | x = self._data[len(self._data) - 1] 11 | del self._data[len(self._data) - 1] 12 | return x 13 | 14 | def peek(self): 15 | return self._data[len(self._data) - 1] 16 | 17 | def empty(self): 18 | self._data = [] 19 | 20 | 21 | def test(): 22 | stack = Stack() 23 | stack.push(1) 24 | stack.push(2) 25 | stack.push(3) 26 | print(stack.pop()) 27 | print(stack.pop()) 28 | stack.empty() 29 | stack.push(4) 30 | stack.push(5) 31 | print(stack.peek()) 32 | stack.push(6) 33 | print(stack.pop()) 34 | print(stack.pop()) 35 | print(stack.pop()) 36 | 37 | 38 | if __name__ == '__main__': 39 | test() 40 | -------------------------------------------------------------------------------- /python/README.md: -------------------------------------------------------------------------------- 1 | ### List of Algorithms: 2 | 3 | #### Searching Algorithms 4 | 5 | * Breadth First Search 6 | * Depth First Search 7 | * Uniform-Cost Search 8 | * Local Search 9 | * Taboo Search 10 | * Beam Search 11 | * Simulated Annealing 12 | 13 | #### Sorting Algorithms 14 | 15 | * Bubble Sort 16 | * Merge Sort 17 | * Sleep Sort 18 | * Quick Sort 19 | 20 | #### Greedy Algorithms 21 | 22 | * Kruskal's Algorithm 23 | 24 | #### Data Structures 25 | 26 | * Stack 27 | * Binomial Coefficient 28 | * Binary Search Tree 29 | -------------------------------------------------------------------------------- /python/Search/BinarySearchTree.py: -------------------------------------------------------------------------------- 1 | 2 | class Node: 3 | 4 | def __init__(self, label): 5 | self.label = label 6 | self.left = None 7 | self.right = None 8 | 9 | def getLabel(self): 10 | return self.label 11 | 12 | def setLabel(self, label): 13 | self.label = label 14 | 15 | def getLeft(self): 16 | return self.left 17 | 18 | def setLeft(self, left): 19 | self.left = left 20 | 21 | def getRight(self): 22 | return self.right 23 | 24 | def setRight(self, right): 25 | self.right = right 26 | 27 | 28 | class BinarySearchTree: 29 | 30 | def __init__(self): 31 | self.root = None 32 | 33 | def insert(self, label): 34 | 35 | # Create a new Node 36 | 37 | node = Node(label) 38 | 39 | if self.empty(): 40 | self.root = node 41 | else: 42 | parent_node = None 43 | cur_node = self.root 44 | 45 | while True: 46 | if cur_node is not None: 47 | 48 | parent_node = cur_node 49 | 50 | if node.getLabel() < cur_node.getLabel(): 51 | cur_node = cur_node.getLeft() 52 | else: 53 | cur_node = cur_node.getRight() 54 | else: 55 | if node.getLabel() < parent_node.getLabel(): 56 | parent_node.setLeft(node) 57 | else: 58 | parent_node.setRight(node) 59 | break 60 | 61 | def empty(self): 62 | if self.root is None: 63 | return True 64 | return False 65 | 66 | def preOrder(self, cur_node): 67 | if cur_node is not None: 68 | print(cur_node.getLabel(), end=" ") 69 | 70 | self.preOrder(cur_node.getLeft()) 71 | self.preOrder(cur_node.getRight()) 72 | 73 | def postOrder(self, cur_node): 74 | if cur_node is not None: 75 | self.postOrder(cur_node.getLeft()) 76 | self.postOrder(cur_node.getRight()) 77 | print(cur_node.getLabel(), end=" ") 78 | 79 | def inOrder(self, cur_node): 80 | if cur_node is not None: 81 | self.inOrder(cur_node.getLeft()) 82 | print(cur_node.getLabel(), end =" ") 83 | self.inOrder(cur_node.getRight()) 84 | 85 | def getRoot(self): 86 | return self.root 87 | 88 | 89 | 90 | t = BinarySearchTree() 91 | t.insert(4) 92 | t.insert(2) 93 | t.insert(1) 94 | t.insert(3) 95 | t.insert(6) 96 | t.insert(5) 97 | t.insert(7) 98 | 99 | 100 | t.preOrder(t.getRoot()) 101 | print("\n") 102 | t.inOrder(t.getRoot()) 103 | print("\n") 104 | t.postOrder(t.getRoot()) 105 | print("\n") 106 | -------------------------------------------------------------------------------- /python/Search/BreadthFirstSearch.py: -------------------------------------------------------------------------------- 1 | 2 | class Graph(): 3 | def __init__(self): 4 | self.vertex = {} 5 | 6 | # for printing the Graph vertexes 7 | def printGraph(self): 8 | for i in self.vertex.keys(): 9 | print(i,' -> ', ' -> '.join([str(j) for j in self.vertex[i]])) 10 | 11 | # for adding the edge beween two vertexes 12 | def addEdge(self, fromVertex, toVertex): 13 | # check if vertex is already present, 14 | if fromVertex in self.vertex.keys(): 15 | self.vertex[fromVertex].append(toVertex) 16 | else: 17 | # else make a new vertex 18 | self.vertex[fromVertex] = [toVertex] 19 | 20 | def BFS(self, startVertex): 21 | # Take a list for stoting already visited vertexes 22 | visited = [False] * len(self.vertex) 23 | 24 | # create a list to store all the vertexes for BFS 25 | queue = [] 26 | 27 | # mark the source node as visited and enqueue it 28 | visited[startVertex] = True 29 | queue.append(startVertex) 30 | 31 | while queue: 32 | startVertex = queue.pop(0) 33 | print(startVertex, end = ' ') 34 | 35 | # mark all adjacent nodes as visited and print them 36 | for i in self.vertex[startVertex]: 37 | if visited[i] == False: 38 | queue.append(i) 39 | visited[i] = True 40 | 41 | if __name__ == '__main__': 42 | g = Graph() 43 | g.addEdge(0, 1) 44 | g.addEdge(0, 2) 45 | g.addEdge(1, 2) 46 | g.addEdge(2, 0) 47 | g.addEdge(2, 3) 48 | g.addEdge(3, 3) 49 | 50 | g.printGraph() 51 | print('BFS:') 52 | g.BFS(2) 53 | 54 | # OUTPUT: 55 | # 0 -> 1 -> 2 56 | # 1 -> 2 57 | # 2 -> 0 -> 3 58 | # 3 -> 3 59 | # BFS: 60 | # 2 0 3 1 61 | -------------------------------------------------------------------------------- /python/Search/Depth-First _Search_Recursive_Function.py: -------------------------------------------------------------------------------- 1 | def dfs_recursive(graph, vertex, path=[]): 2 | path += [vertex] 3 | 4 | for neighbor in graph[vertex]: 5 | if neighbor not in path: 6 | path = dfs_recursive(graph, neighbor, path) 7 | 8 | return path 9 | 10 | 11 | adjacency_matrix = {1: [2, 3], 2: [4, 5], 12 | 3: [5], 4: [6], 5: [6], 13 | 6: [7], 7: []} 14 | 15 | print(dfs_recursive(adjacency_matrix, 1)) 16 | # [1, 2, 4, 6, 7, 5, 3] 17 | -------------------------------------------------------------------------------- /python/Sorts/bubble_sort.py: -------------------------------------------------------------------------------- 1 | """ 2 | https://en.wikipedia.org/wiki/Bubble_sort 3 | Worst-case performance: O(N^2) 4 | """ 5 | 6 | 7 | def bubble_sort(arr): 8 | 9 | def swap(i, j): 10 | arr[i], arr[j] = arr[j], arr[i] 11 | 12 | n = len(arr) 13 | swapped = True 14 | while swapped: 15 | swapped = False 16 | for i in range(1, n): 17 | if arr[i - 1] > arr[i]: 18 | swap(i - 1, i) 19 | swapped = True 20 | 21 | array = [1, 5, 65, 23, 57, 1232, -1, -5, -2, 242, 100, 22 | 4, 423, 2, 564, 9, 0, 10, 43, 64, 32, 1, 999] 23 | print(array) 24 | bubble_sort(array) 25 | print(array) 26 | -------------------------------------------------------------------------------- /python/Sorts/merge_sort.py: -------------------------------------------------------------------------------- 1 | # Logic: Divide and Conquer 2 | # Time Complexity: O(nlogn) [average case] 3 | # Not inplace sort 4 | 5 | 6 | 7 | def mergeArr(arr1, arr2): 8 | 9 | arr3= [] 10 | i,j=0,0 11 | 12 | while(i 0 and len(right) > 0: 22 | #Look at the first element of the left and right arrays 23 | #And add the smaller one to the output array 24 | if left[0] < right[0]: 25 | array.append(left[0]) 26 | del left[0] 27 | else: 28 | array.append(right[0]) 29 | del right[0] 30 | #When the loop ends either left or right will have element(s) left in it 31 | if len(left) > 0: 32 | return array + left 33 | if len(right) > 0: 34 | return array + right 35 | 36 | -------------------------------------------------------------------------------- /python/Sorts/quick_sort.py: -------------------------------------------------------------------------------- 1 | # Implementation of Quick Sort in Python 2 | # Last Edited 10/21/17 (implemented qsort_firstE(arr)) 3 | # Worst case performance: O(n^2) 4 | # Average performance: O(nlogn) 5 | 6 | # In this first implementation of quick sort, the choice of pivot 7 | # is always the first element in the array, namely arr[0] 8 | def qsort_firstE(arr): 9 | # if the array is empty, return the empty array 10 | if not arr: 11 | return arr 12 | # otherwise, partition the array around the pivot, and concatenate 13 | # the recursively sorted arrays 14 | else: 15 | left = [x for x in arr[1:] if x < arr[0]] 16 | right = [x for x in arr[1:] if x >= arr[0]] 17 | return qsort_firstE(left) + [arr[0]] + qsort_firstE(right) 18 | 19 | # Test case 1. 20 | # quicksorting an empty array returns an empty array 21 | print(qsort_firstE([])) 22 | # Test case 2. 23 | # quicksorting an array with negative, repeating values 24 | print(qsort_firstE([3, 6, 82, 23, -4, -102, 23, -8, 3, 0])) 25 | -------------------------------------------------------------------------------- /python/Sorts/quicksort.py: -------------------------------------------------------------------------------- 1 | 2 | def quicksort(array=[12,4,5,6,7,3,1,15]): 3 | less = [] 4 | equal = [] 5 | greater = [] 6 | if len(array) > 1: 7 | pivot = array[0] 8 | for x in array: 9 | if x < pivot: 10 | less.append(x) 11 | if x == pivot: 12 | equal.append(x) 13 | if x > pivot: 14 | greater.append(x) 15 | return sort(less)+equal+sort(greater) 16 | else: 17 | return array 18 | -------------------------------------------------------------------------------- /python/Sorts/radix_sort: -------------------------------------------------------------------------------- 1 | def radixsort(L): 2 | # Only works for lists of non-negative integers! 3 | maxValue = max(L) 4 | def rsort(L, digitSelector): 5 | if (digitSelector > maxValue): 6 | return L 7 | else: 8 | zeroes = [x for x in L if (x & digitSelector == 0)] 9 | ones = [x for x in L if (x & digitSelector != 0)] 10 | return rsort(zeroes + ones, digitSelector << 1) 11 | return rsort(L, 1) 12 | -------------------------------------------------------------------------------- /python/Sorts/selection_sort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(lst): 2 | 3 | 4 | for j in range(len(lst)): 5 | min=lst[j];index=j 6 | for i in range(j,len(lst)): 7 | if min>lst[i]: 8 | index=i 9 | min=lst[i] 10 | 11 | (lst[index],lst[j])=(lst[j],min) 12 | print(lst) 13 | 14 | 15 | 16 | 17 | selectionSort([0,5,8,9,56,3,1,5]) 18 | -------------------------------------------------------------------------------- /python/Sorts/shell_sort.py: -------------------------------------------------------------------------------- 1 | def shellSort(items,k): 2 | if k==0: 3 | k=2 4 | inc = len(items) // k 5 | while inc: 6 | for i in range(len(items)): 7 | j = i 8 | temp = items[i] 9 | while j >= inc and items[j-inc] > temp: 10 | items[j] = items[j - inc] 11 | j -= inc 12 | items[j] = temp 13 | inc = inc//k if inc//k else (0 if inc==1 else 1) 14 | print(items) 15 | 16 | 17 | shellSort([234,5,67,8,-2,4,67,8,90,90,0,5],8) 18 | 19 | 20 | -------------------------------------------------------------------------------- /python/Sorts/sleep_sort.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | from time import sleep 3 | from random import randint 4 | 5 | description = """ 6 | ************************************************************************************ 7 | SLEEP SORT: 8 | 1. Create a thread for each array element 9 | 2. Each thread sleeps for an amount of time proportional to its array element's value 10 | 3. Each thread then appends its value to the sorted array after sleeping 11 | 12 | - Works with negative numbers if you add (negation of lowest number in list) to every element in the list, 13 | run sleep sort, then subtract back the number to every element. 14 | - Limitations include being extremely slow if input array has a huge number 15 | ************************************************************************************ 16 | """ 17 | 18 | state = { 'sorted_list': [] } 19 | 20 | def sleep_sort(numbers): 21 | state['sorted_list'] = [] 22 | state['length'] = len(numbers) 23 | threads = [Thread(target=_appender, args=(number,)) for number in numbers] 24 | [t.start() for t in threads] 25 | [t.join() for t in threads] 26 | 27 | return state['sorted_list'] 28 | 29 | def _appender(number): 30 | sleep(number) 31 | state['sorted_list'].append(number) 32 | 33 | def test(): 34 | unsorted = [randint(0, 9) for _ in range(10)] 35 | print('Using randomly-generated unsorted list: [%s]' % ', '.join(str(i) for i in unsorted)) 36 | sorted_list = sleep_sort(unsorted) 37 | print('Got sleep-sorted list: [%s]' % ', '.join(str(i) for i in sorted_list)) 38 | print('This should print True: %s' % (sorted(unsorted) == sorted_list)) 39 | 40 | if __name__ == '__main__': 41 | print(description) 42 | print('This should take no more than 10 seconds') 43 | test() 44 | -------------------------------------------------------------------------------- /python/binomial_coefficients.py: -------------------------------------------------------------------------------- 1 | # Complexity: O(n^2) 2 | # Computes the lines of Pascal's triangle. 3 | # Pascal's triangle gives us result of binom(n,p), which is equivalent to combination(n,p). 4 | 5 | import fileinput 6 | 7 | binomial_coefficients = [] 8 | line = [] 9 | line.append(1) 10 | binomial_coefficients.append(line) 11 | 12 | # Element at line x and column y(binom[x][y]) of Pascal's triangle can be calculated as (binom[x-1][y] + binom[x-1][y-1]). 13 | def precomp(n): 14 | for i in range(1,n): 15 | line = [] 16 | line.append(1) 17 | 18 | for j in range(1,i): 19 | line.append(binomial_coefficients[i - 1][j] + binomial_coefficients[i - 1][j - 1]) 20 | 21 | line.append(1) 22 | 23 | binomial_coefficients.append(line) 24 | 25 | precomp(40) 26 | 27 | for line in fileinput.input(): 28 | n,p = line.strip().split() 29 | n = int(n) 30 | p = int(p) 31 | 32 | print(binomial_coefficients[n][p]) 33 | -------------------------------------------------------------------------------- /ruby/Search/linear_search.ruby: -------------------------------------------------------------------------------- 1 | class LinearSearch 2 | # This function returns index of element x in arr[] 3 | def self.search(array, search_term) 4 | array.each_with_index do |elem, index| 5 | if elem == search_term 6 | return index 7 | end 8 | -1 9 | end 10 | end 11 | end 12 | 13 | 14 | # Example 15 | array = ['Hi', 'Hola', 'Iorana'] 16 | LinearSearch.search(array, 'Hola') => 1 17 | LinearSearch.search(array, 'Hi') => 0 18 | LinearSearch.search(array, 'Iorana') => 2 19 | -------------------------------------------------------------------------------- /ruby/Sorting_algorithms/bubble_sort.rb: -------------------------------------------------------------------------------- 1 | def bubble_sort(array) 2 | return array if array.size <= 1 3 | swap = true 4 | while swap 5 | swap = false 6 | (array.length - 1).times do |x| 7 | if array[x] > array[x+1] 8 | array[x], array[x+1] = array[x+1], array[x] 9 | swap = true 10 | end 11 | end 12 | end 13 | array 14 | end -------------------------------------------------------------------------------- /ruby/Sorting_algorithms/merge_sort.rb: -------------------------------------------------------------------------------- 1 | 2 | class MergeSortAlgorithm 3 | # Break's the array down into two numbers (number A and number B) and sorts them. 4 | def sort(numbers) 5 | if numbers.size <= 1 6 | return numbers 7 | end 8 | 9 | array_size = numbers.size 10 | half_of_size = (array_size / 2).round 11 | 12 | left_array = numbers.take(half_of_size) 13 | right_array = numbers.drop(half_of_size) 14 | 15 | sorted_left_array = sort(left_array) 16 | sorted_right_array = sort(right_array) 17 | 18 | merge(sorted_left_array, sorted_right_array) 19 | end 20 | 21 | # This then creates a new array, loops through the left/right arrays and places the lowest number into the array. 22 | def merge(left_array, right_array) 23 | if right_array.empty? 24 | return left_array # We have nothing to compare. Left wins. 25 | end 26 | 27 | if left_array.empty? 28 | return right_array # We have nothing to compare. Right wins. 29 | end 30 | 31 | smallest_number = if left_array.first <= right_array.first 32 | left_array.shift 33 | else 34 | right_array.shift 35 | end 36 | 37 | # We keep doing it until the left or right array is empty. 38 | recursive = merge(left_array, right_array) 39 | 40 | # Okay, either left or right array are empty at this point. So we have a result. 41 | [smallest_number].concat(recursive) 42 | end 43 | end 44 | 45 | # Let's give this a spin? 46 | merge_sort = MergeSortAlgorithm.new 47 | puts merge_sort.sort([4, 92, 1, 39, 19, 93, 49, 10].shuffle) # => [1, 4, 10, 19, 39, 49, 92, 93] -------------------------------------------------------------------------------- /scala/Search/linear_search.scala: -------------------------------------------------------------------------------- 1 | object linear_search{ 2 | 3 | def linear_search(arr : List[Int], ele : Int) : Int = { 4 | 5 | def go (l : List[Int], i : Int) : Int = { 6 | l match { 7 | //If list is empty return -1 8 | case List() => -1 9 | //Return the index of element if found 10 | case x :: xs if x == ele => i + 1 11 | //return -1 if not found 12 | case x :: Nil if x != ele => -1 13 | //else recursively call 14 | case x :: xs if x != ele => go(xs, i+1) 15 | } 16 | } 17 | 18 | go(arr, -1) 19 | 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /scala/Sorting_algorithms/quicksort.scala: -------------------------------------------------------------------------------- 1 | object Quicksort { 2 | def quicksort[T](cmp: (T,T) => Boolean, list: List[T]) : List[T] = { 3 | list match { 4 | case Nil => 5 | Nil 6 | case pivot::tl => 7 | val (e1, e2) = tl.partition( (X: T) => cmp(X, pivot) ) 8 | quicksort(cmp, e1) ::: (pivot::Nil) ::: quicksort(cmp, e2) 9 | } 10 | } 11 | } 12 | 13 | --------------------------------------------------------------------------------