├── Algorithm Collections ├── QuickSort.cpp └── selectionSort.cpp ├── Data Structures ├── BinaryTree │ └── BinaryTree.go ├── Doubly Linked List │ └── DoublyLinkedList.java ├── HashTable │ ├── HashEntry.java │ ├── HashTable.java │ └── HashTableImp.java ├── LinkedList │ ├── LinkedList.java │ ├── List.java │ ├── SinglyLinkedList.swift │ └── linked_list.c ├── Queue │ ├── Queue.go │ ├── Queue.java │ ├── Queue.js │ ├── Queue_test.go │ └── queue.c └── Stack │ ├── Stack Using Java │ ├── Stack.java │ └── stackNode.java │ ├── Stack.go │ ├── Stack.java │ └── stack.c ├── Dynamic Programming ├── Fibonacci Series │ └── Fibonacci.java └── Longest Palindrome Substring │ └── LongestPalindromeSubstring.java ├── Greedy Algorithms └── Knapsack │ └── Fractional Knapsack │ └── Fractional_Knapsack.cpp ├── Mathematical Algorithms ├── Factorization │ └── factorial.cpp └── GCD │ └── gcd.cpp ├── README.md ├── Search Algorithms ├── Binary Search │ ├── BinarySearch.c │ └── BinarySearch.java ├── Breath First Search │ └── bfs.cpp ├── Interpolation Search │ └── InterpolationSearch.java └── Linear Search │ ├── Linear Search.c │ └── LinearSearch.java ├── Sorting Algorithms ├── Bubble Sort │ ├── BubbleSort.c │ ├── BubbleSort.java │ ├── BubbleSort.swift │ ├── bubble sort.py │ ├── bubbleSort.java │ ├── bubble_sort.cpp │ └── bubble_sort.go ├── Heap Sort │ ├── HeapSort.c │ └── HeapSort.java ├── Insertion Sort │ ├── InsertionSort.java │ ├── InsertionSort.ts │ └── insertion sort.c ├── Quick Sort │ ├── QuickSort.java │ └── Quick_Sort.cpp ├── Radix Sort │ └── RadixSort.java ├── Selection sort │ ├── SelectionSort.c │ ├── SelectionSort.class │ ├── SelectionSort.go │ └── SelectionSort.java └── Shell Sort │ └── ShellSort.java └── String Algorithms ├── KMP └── kmp.c └── Palindrome ├── Palindrome.java └── palindrome.js /Algorithm Collections/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void quickSort(int A[], int low, int high); 5 | void swap(int &a, int &b); 6 | int partition(int A[], int low, int high); 7 | 8 | int main() 9 | { 10 | 11 | int arr[] = {20, 10, 24, 14, 12, 0, 8, 5, 9, 21}; 12 | 13 | cout << "\nBefore\n"; 14 | for (int i = 0; i < 10; i++) 15 | { 16 | cout << arr[i] << " "; 17 | } 18 | 19 | quickSort(arr, 0, 9); 20 | 21 | cout << "\n\nAfter\n"; 22 | for (int i = 0; i < 10; i++) 23 | { 24 | cout << arr[i] << " "; 25 | } 26 | 27 | return 0; 28 | } 29 | 30 | int partition(int A[], int low, int high) 31 | { 32 | int pivot = A[low]; 33 | int i = low + 1; 34 | int j = high; 35 | int temp; 36 | do 37 | { 38 | while (A[i] <= pivot) 39 | { 40 | i++; 41 | } 42 | while (A[j] > pivot) 43 | { 44 | j--; 45 | } 46 | if (i < j) 47 | { 48 | temp = A[i]; 49 | A[i] = A[j]; 50 | A[j] = temp; 51 | } 52 | } while (i < j); 53 | // Swap A[low] and A[j] 54 | temp = A[low]; 55 | A[low] = A[j]; 56 | A[j] = temp; 57 | return j; 58 | } 59 | 60 | void quickSort(int A[], int low, int high) 61 | { 62 | int partitionIndex; 63 | if (low < high) 64 | { 65 | partitionIndex = partition(A, low, high); 66 | quickSort(A, low, partitionIndex - 1); 67 | quickSort(A, partitionIndex + 1, high); 68 | } 69 | } 70 | void swap(int &a, int &b) 71 | { 72 | int temp = a; 73 | a = b; 74 | b = a; 75 | } 76 | -------------------------------------------------------------------------------- /Algorithm Collections/selectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void selectionSort(int a[],int size); 5 | void printArray(int a[],int size); 6 | 7 | int main(){ 8 | 9 | int n; 10 | cout<<"Enter the size of the array: "; 11 | cin>>n; 12 | 13 | int arr[n]; 14 | 15 | cout<<"Enter the array to be sorted : \n"; 16 | 17 | for(int i=0;i>arr[i]; 19 | } 20 | 21 | cout<<"\nInitial Array : \n"; 22 | printArray(arr,n); 23 | 24 | selectionSort(arr,n); 25 | 26 | cout<<"\nFinal Sorted (ascending) Array : \n"; 27 | printArray(arr,n); 28 | 29 | return 0; 30 | } 31 | 32 | 33 | void selectionSort(int a[],int size){ 34 | int min; 35 | for(int i=0;ia[j]){ 39 | min=j; 40 | } 41 | } 42 | int temp=a[min]; 43 | a[min]=a[i]; 44 | a[i]=temp; 45 | } 46 | } 47 | 48 | void printArray(int a[],int size){ 49 | for(int i=0;i for the HashTable implementation 3 | * @author MarceStarlet 4 | */ 5 | public class HashEntry implements Comparable>{ 6 | 7 | private int key; 8 | private E value; 9 | 10 | public HashEntry(int key, E value){ 11 | this.key = key; 12 | this.value = value; 13 | } 14 | 15 | /** 16 | * @return int key 17 | */ 18 | public int getKey() { 19 | return key; 20 | } 21 | 22 | /** 23 | * @return E value 24 | */ 25 | public E getValue() { 26 | return value; 27 | } 28 | 29 | /** 30 | * set E value 31 | * @param value 32 | */ 33 | public void setValue(E value){ 34 | this.value = value; 35 | } 36 | 37 | @Override 38 | public int hashCode(){ 39 | return key; 40 | } 41 | 42 | @Override 43 | public int compareTo(HashEntry o) { 44 | // compare for keys 45 | return this.key == o.key ? 0 : -1; 46 | } 47 | 48 | @Override 49 | @SuppressWarnings("unchecked") 50 | public boolean equals(Object o){ 51 | // define equals from keys 52 | return ((HashEntry) o).getKey() == this.getKey() ? true : false; 53 | } 54 | 55 | } 56 | -------------------------------------------------------------------------------- /Data Structures/HashTable/HashTable.java: -------------------------------------------------------------------------------- 1 | /** 2 | * HashTable 3 | * Separate chaining with linked list to prevent collisions 4 | * HashTable for an HashEntry 5 | * @author MarceStarlet 6 | * @param 7 | */ 8 | public interface HashTable { 9 | 10 | /** 11 | * get value from the key given 12 | * @param key 13 | * @return 14 | */ 15 | T get(int key); 16 | 17 | /** 18 | * put the value for the key given 19 | * @param key 20 | * @param value 21 | */ 22 | void put(int key, T value); 23 | } 24 | -------------------------------------------------------------------------------- /Data Structures/HashTable/HashTableImp.java: -------------------------------------------------------------------------------- 1 | import java.util.LinkedList; 2 | import java.util.Optional; 3 | 4 | /** 5 | * HashTable Implementation 6 | * Separate chaining with linked list to prevent collisions 7 | * HashTable for an HashEntry 8 | * @author MarceStarlet 9 | */ 10 | public class HashTableImp implements HashTable{ 11 | 12 | // the HashTable maximum size 13 | private static int HASTABLE_SIZE = 128; 14 | // the linked list of HashEntry type 15 | private LinkedList>[] hashTable; 16 | 17 | @SuppressWarnings("unchecked") 18 | public HashTableImp(){ 19 | hashTable = new LinkedList[HASTABLE_SIZE]; 20 | for(int i = 0; i < HASTABLE_SIZE; i++){ 21 | hashTable[i] = null; 22 | } 23 | } 24 | 25 | @Override 26 | public T get(int key) { 27 | // hash the key 28 | int hash = hashInt(key); 29 | // get the linked list in the hash position 30 | LinkedList> entryList = hashTable[hash]; 31 | 32 | // return if null 33 | if(entryList == null) 34 | return null; 35 | 36 | // filter for the key and return the value 37 | Optional> found = entryList.stream().filter(e -> e.getKey() == key).findFirst(); 38 | 39 | return found.isPresent() ? found.get().getValue() : null; 40 | } 41 | 42 | @Override 43 | public void put(int key, T value) { 44 | // hash the key 45 | int hash = hashInt(key); 46 | // create new HashEntry 47 | HashEntry entry = new HashEntry(key, value); 48 | // get the linked list in the hash position 49 | LinkedList> entryList = hashTable[hash]; 50 | 51 | // if the position is null then create new LinkedList 52 | // and add the new HashEntry to the list 53 | if(null == entryList){ 54 | entryList = new LinkedList>(); 55 | entryList.add(entry); 56 | }else{ 57 | // else, ask if the new entry exists 58 | // if exists, replace the value 59 | // if does not exists, add to the current list 60 | int exists = entryList.indexOf(entry); 61 | if(exists >= 0){ 62 | entryList.get(exists).setValue(value); 63 | }else{ 64 | entryList.add(entry); 65 | } 66 | } 67 | // assign the new list in the hash position 68 | hashTable[hash] = entryList; 69 | } 70 | 71 | /** 72 | * @param key 73 | * @return hash code for the key given 74 | */ 75 | private int hashInt(int key){ 76 | // simple hash, module of the key 77 | return key % HASTABLE_SIZE; 78 | } 79 | 80 | @Override 81 | public String toString(){ 82 | StringBuilder str = new StringBuilder(); 83 | LinkedList> entryList; 84 | str.append("HashTable=["); 85 | for(int i = 0; i < HASTABLE_SIZE; i++){ 86 | entryList = hashTable[i]; 87 | if(null != entryList){ 88 | entryList.stream().forEach(e -> str.append("{").append(e.getKey()) 89 | .append(",").append(e.getValue()).append("}").append(",")); 90 | } 91 | } 92 | str.replace(str.length()-1, str.length(), ""); 93 | str.append("]"); 94 | 95 | return str.toString(); 96 | } 97 | 98 | } 99 | -------------------------------------------------------------------------------- /Data Structures/LinkedList/LinkedList.java: -------------------------------------------------------------------------------- 1 | /** 2 | * LinkedList implementation 3 | * A single linked list implementation with the four 4 | * basic operations: add, remove, get and size. 5 | * This linked list implementation uses an internal Node class 6 | * to keep the value and the pointer to the next Node in the list 7 | * @param 8 | */ 9 | public class LinkedList implements List{ 10 | 11 | // the head of the list 12 | private Node head; 13 | // to handle the size of the list 14 | private int size = 0; 15 | 16 | public LinkedList(){ 17 | // init the head with an empty Node 18 | this.head = new Node<>(); 19 | } 20 | 21 | 22 | @Override 23 | public boolean add(T value) { 24 | try{ 25 | Node aux = this.head; // we always start at head 26 | while ( aux.getNext() != null ){ // get next Node until getNext() != null 27 | aux = aux.getNext(); 28 | } 29 | 30 | aux.setNext( new Node<>( value ) ); // create new Node using the value passed 31 | size = size + 1; 32 | }catch ( Exception e ){ 33 | return false; 34 | } 35 | return true; 36 | } 37 | 38 | @Override 39 | public boolean remove(int index) throws IndexOutOfBoundsException { 40 | // index is not valid? 41 | if( index < 0 || index > size() ) { 42 | throw new IndexOutOfBoundsException(); 43 | } 44 | 45 | Node aux = this.head; // we always start at head 46 | try{ 47 | for (int i = 0; i < index && aux.getNext() != null; i++) { // iterate up to index 48 | aux = aux.getNext(); 49 | } 50 | 51 | // remove the Node by re-assign the 'Node.next' to the next Node in the list 52 | aux.setNext( aux.getNext().getNext() ); 53 | size = size - 1; 54 | }catch ( Exception e ){ 55 | return false; 56 | } 57 | 58 | return true; 59 | } 60 | 61 | /** 62 | * Removes the first occurrence of the value from the list 63 | * @param value 64 | * @return true if succeed 65 | */ 66 | public boolean remove(T value) { 67 | Node aux = this.head; // we always start at head 68 | if (null != value) { 69 | while (!value.equals(aux.getNext().getValue())) { // iterate until values are equals 70 | aux = aux.getNext(); 71 | } 72 | 73 | // remove the Node by re-assign the 'Node.next' to the next Node in the list 74 | aux.setNext(aux.getNext().getNext()); 75 | size = size - 1; 76 | }else{ 77 | return false; 78 | } 79 | 80 | return true; 81 | } 82 | 83 | @Override 84 | public T get(int index) throws IndexOutOfBoundsException { 85 | // index is not valid? 86 | if( index < 0 || index > size() ) { 87 | throw new IndexOutOfBoundsException(); 88 | } 89 | 90 | Node aux = this.head; // we always start at head 91 | for (int i = 0; i <= index && aux.getNext() != null; i++){ // iterate up to index 92 | aux = aux.getNext(); 93 | } 94 | 95 | return aux.getValue(); 96 | } 97 | 98 | @Override 99 | public int size() { 100 | return size; 101 | } 102 | 103 | @Override 104 | public String toString(){ 105 | StringBuilder str = new StringBuilder(""); 106 | str.append("LinkedList={"); 107 | 108 | Node aux = this.head; // we always start at head 109 | while ( aux.getNext() != null ) { 110 | aux = aux.getNext(); 111 | str.append( aux.toString() ).append(","); 112 | } 113 | str.replace(str.length()-1, str.length(), "}"); 114 | 115 | return str.toString(); 116 | } 117 | 118 | /** 119 | * Node abstracts the elements in the list, keeps 120 | * the value and points to the next Node in the list 121 | * @param 122 | */ 123 | class Node { 124 | 125 | private E value; 126 | private Node next; 127 | 128 | public Node( E value ){ 129 | this.value = value; 130 | } 131 | 132 | public Node() { 133 | 134 | } 135 | 136 | public E getValue() { 137 | return value; 138 | } 139 | 140 | public Node getNext() { 141 | return next; 142 | } 143 | 144 | public void setNext(Node next) { 145 | this.next = next; 146 | } 147 | 148 | @Override 149 | public String toString(){ 150 | return this.getValue().toString(); 151 | } 152 | } 153 | } 154 | -------------------------------------------------------------------------------- /Data Structures/LinkedList/List.java: -------------------------------------------------------------------------------- 1 | /** 2 | * List 3 | * A simple list definition with the four 4 | * basic operations: add, remove, get and size. 5 | * @author MarceStarlet 6 | * @param 7 | */ 8 | public interface List { 9 | 10 | /** 11 | * Adds a value to the end of the list 12 | * @param value 13 | * @return true if succeed 14 | */ 15 | boolean add( T value ); 16 | 17 | /** 18 | * Removes the value in the position index 19 | * @param index 20 | * @return true if succeed 21 | * @throws IndexOutOfBoundsException whether (index < 0 or index > size()) 22 | */ 23 | boolean remove( int index ) throws IndexOutOfBoundsException; 24 | 25 | /** 26 | * Gets the value in the position index 27 | * @param index 28 | * @return value type T 29 | * @throws IndexOutOfBoundsException whether (index < 0 or index > size()) 30 | */ 31 | T get( int index ) throws IndexOutOfBoundsException; 32 | 33 | /** 34 | * @return the number of elements in the list 35 | */ 36 | int size(); 37 | } 38 | -------------------------------------------------------------------------------- /Data Structures/LinkedList/SinglyLinkedList.swift: -------------------------------------------------------------------------------- 1 | // Created by Dilum De Silva on 2021-10-19. 2 | // 3 | // Type: Singly Linked List 4 | // Usage: var list = LinkedList() 5 | 6 | import Foundation 7 | 8 | public class Node { 9 | var value: T //This could be any datatype you want to store in linked-list 10 | var next: Node? 11 | 12 | init(value: T, next: Node? = nil) { 13 | self.value = value 14 | self.next = next 15 | } 16 | } 17 | 18 | struct LinkedList { 19 | 20 | var head: Node? 21 | var tail: Node? 22 | 23 | var isEmpty: Bool { head == nil } 24 | 25 | init() {} 26 | 27 | //To replace the current head and add data to the front 28 | mutating func push(_ value: T) { 29 | head = Node(value: value, next: head) 30 | 31 | if tail == nil { 32 | tail = head 33 | } 34 | } 35 | 36 | //To remove the head (LIFO) 37 | mutating func pop() -> T? { 38 | defer { 39 | head = head?.next 40 | 41 | if isEmpty { 42 | tail = nil 43 | } 44 | } 45 | return head?.value 46 | } 47 | 48 | //To add data to the end of list 49 | mutating func append(_ value: T) { 50 | let node = Node(value: value) 51 | 52 | tail?.next = node 53 | tail = node 54 | } 55 | 56 | //To retreive data from a node index 57 | func node(at index: Int) -> Node? { 58 | var currentIndex = 0 59 | var currentNode = head 60 | 61 | while currentNode != nil && currentIndex < index { 62 | currentNode = currentNode?.next 63 | currentIndex += 1 64 | } 65 | 66 | return currentNode 67 | } 68 | 69 | //To insert a node at a given position 70 | func insert(_ value: T, after index: Int) { 71 | guard let node = node(at: index) else { return } 72 | node.next = Node(value: value, next: node.next) 73 | } 74 | 75 | //TODO: Remove Last - to remove the tail 76 | //TODO: Remove After - to remove a node after an index 77 | } 78 | -------------------------------------------------------------------------------- /Data Structures/LinkedList/linked_list.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | 6 | //self referencing structure with one data element 7 | struct Node { 8 | int data; 9 | struct Node *next; 10 | }; 11 | 12 | 13 | // Aliasing for easier referencing 14 | typedef struct Node Node; 15 | 16 | /*-------------------------------------- Linked List Functions -------------------------------------- */ 17 | /** Ideally these should go in a seperate Header file (ie. linked_list.h) along with the self referencing structures 18 | * 19 | * Linked List Functions 20 | * Create Node : create_node 21 | * Insert : insert_head, insert_tail, insert_next_to 22 | * Update : update 23 | * Search : search 24 | * Delete : delete 25 | * Display List : print_list 26 | * 27 | */ 28 | 29 | // Creates a Node in Heap and returns a pointer 30 | Node * create_node(int data){ 31 | Node *node = malloc(1 * sizeof(Node)); 32 | node->data = data; 33 | node->next = NULL; 34 | 35 | return node; 36 | } 37 | 38 | // Searches for the given value and returns the node if found 39 | Node * search(Node *head, int value) { 40 | 41 | while(head != NULL) { 42 | if(head->data == value) { 43 | return head; 44 | } 45 | 46 | head = head->next; 47 | } 48 | 49 | return NULL; 50 | } 51 | 52 | 53 | // appends a node to the end of the Linked List 54 | void insert_tail(Node **head, int data) { 55 | if(*head == NULL) { 56 | *head = create_node(data); 57 | }else { 58 | Node *current = *head; 59 | 60 | while(current->next != NULL) { 61 | current = current->next; 62 | } 63 | 64 | current->next = create_node(data); 65 | } 66 | } 67 | 68 | // appends a node to the beginning of the Linked List 69 | void insert_head(Node **head, int data) { 70 | Node *new_node = create_node(data); 71 | 72 | new_node->next = *head; 73 | *head = new_node; 74 | } 75 | 76 | // appends the node next to the node with given value 77 | void insert_next_to(Node *head, int next_to, int data) { 78 | Node *search_result = search(head, next_to); 79 | 80 | if(search_result != NULL) { 81 | Node *new_node = create_node(data); 82 | 83 | new_node->next = search_result->next; 84 | search_result->next = new_node; 85 | }else { 86 | printf("Insert Failed : No such value found!!\n"); 87 | } 88 | } 89 | 90 | // Updates specific element in the Linked List 91 | void update(Node *head, int old_value, int new_value) { 92 | Node *search_result = search(head, old_value); 93 | 94 | if(search_result != NULL) { 95 | search_result->data = new_value; 96 | }else { 97 | printf("Update Failed : Value not found!!\n"); 98 | } 99 | } 100 | 101 | // looks for (int value) and deletes the first node containing (int value) if found 102 | int delete(Node **head, int value) { 103 | if(*head == NULL) { 104 | printf("Delete Faied : Empty List\n"); 105 | return -1; 106 | } 107 | 108 | Node *current = *head; 109 | Node *previous = NULL; 110 | 111 | while(current != NULL) { 112 | if(current->data == value) { 113 | break; 114 | } 115 | 116 | previous = current; 117 | current = current->next; 118 | } 119 | 120 | if(current == NULL) { 121 | printf("Delete Faied : Value not found!!\n"); 122 | return -1; 123 | }else { 124 | if(current == *head) { 125 | *head = (*head)->next; 126 | }else { 127 | previous->next = current->next; 128 | } 129 | 130 | int deleted = current->data; 131 | 132 | free(current); 133 | 134 | printf("Successfully deleted %d\n", deleted); 135 | 136 | return deleted; 137 | } 138 | } 139 | 140 | 141 | // Prints all the elements in the linked list 142 | void print_list(Node *head) { 143 | if(head == NULL) { 144 | printf("Empty List !!\n"); 145 | }else { 146 | 147 | printf("["); 148 | 149 | while(head != NULL) { 150 | printf(" %d", head->data); 151 | 152 | if(head->next != NULL) printf(","); 153 | 154 | head = head->next; 155 | } 156 | 157 | printf(" ]\n"); 158 | } 159 | } 160 | 161 | /* --------------------------------- End of Linked List Functions ----------------------------------- */ 162 | 163 | int main() { 164 | Node *head = NULL; // Pointer to the First Node of the Linked List 165 | 166 | insert_tail(&head, 10); 167 | insert_tail(&head, 50); 168 | 169 | insert_head(&head, 5); 170 | 171 | insert_next_to(head, 10, 11); 172 | 173 | update(head, 10, 19); 174 | 175 | delete(&head, 19); 176 | 177 | print_list(head); 178 | 179 | return 0; 180 | } -------------------------------------------------------------------------------- /Data Structures/Queue/Queue.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | // Queue object represents an array which items are pushed to 4 | type Queue []interface{} 5 | 6 | // Enqueue adds an object to the queue 7 | func (q *Queue) Enqueue(item interface{}) { 8 | *q = append(*q, item) 9 | } 10 | 11 | // Dequeue takes removes and returns the first value of the queue 12 | func (q *Queue) Dequeue() interface{} { 13 | item := (*q)[0] 14 | queue := *q 15 | newQueue := queue[1:] 16 | *q = newQueue 17 | return item 18 | } 19 | 20 | // Peek returns the first value of the queue without removing it 21 | func (q *Queue) Peek() interface{} { 22 | return (*q)[0] 23 | } 24 | 25 | // Empty clears the queue 26 | func (q *Queue) Empty() { 27 | *q = Queue{} 28 | } 29 | 30 | // IsEmpty returns if the queue is empty or not 31 | func (q *Queue) IsEmpty() bool { 32 | return len(*q) == 0 33 | } 34 | 35 | // Length returns the length of the queue 36 | func (q *Queue) Length() int { 37 | return len(*q) 38 | } 39 | -------------------------------------------------------------------------------- /Data Structures/Queue/Queue.java: -------------------------------------------------------------------------------- 1 | public class Queue { 2 | 3 | private QueueNode front; 4 | private QueueNode back; 5 | 6 | Queue(){ 7 | this.front = null; 8 | this.back = null; 9 | } 10 | 11 | 12 | boolean isEmpty() { 13 | if(this.front == null) { 14 | return true; 15 | }else { 16 | return false; 17 | } 18 | } 19 | 20 | void enqueue(int data) { 21 | QueueNode newNode = new QueueNode(data); 22 | 23 | if(isEmpty()) { 24 | this.front = newNode; 25 | this.back = newNode; 26 | }else { 27 | this.back.setNext(newNode); 28 | this.back = newNode; 29 | } 30 | } 31 | 32 | int dequeue() { 33 | 34 | if(isEmpty()) { 35 | return 0; 36 | }else { 37 | QueueNode temp = this.front; 38 | this.front = this.front.getNext(); 39 | 40 | if(this.front == null) { 41 | this.back = null; 42 | } 43 | 44 | return temp.getData(); 45 | } 46 | } 47 | 48 | void peek() { 49 | if(isEmpty()) { 50 | System.out.println("Empty Queue"); 51 | }else { 52 | System.out.println(this.front.getData()); 53 | } 54 | } 55 | 56 | void print() { 57 | QueueNode temp = this.front; 58 | 59 | while(!isEmpty()) { 60 | System.out.print(dequeue() +" "); 61 | temp = temp.getNext(); 62 | } 63 | } 64 | } 65 | 66 | class QueueNode { 67 | 68 | //you can define any type of data in here 69 | private int data; 70 | private QueueNode next; 71 | 72 | QueueNode(int data){ 73 | this.data = data; 74 | this.next = null; 75 | } 76 | 77 | public int getData() { 78 | return data; 79 | } 80 | 81 | public void setData(int data) { 82 | this.data = data; 83 | } 84 | 85 | public QueueNode getNext() { 86 | return next; 87 | } 88 | 89 | public void setNext(QueueNode next) { 90 | this.next = next; 91 | } 92 | 93 | 94 | 95 | } -------------------------------------------------------------------------------- /Data Structures/Queue/Queue.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | class Queue { 4 | constructor() { 5 | this.empty(); 6 | } 7 | 8 | /** 9 | * Adds an item to the end of the queue 10 | * @param item 11 | */ 12 | enqueue(item) { 13 | this._queue.push(item); 14 | } 15 | 16 | /** 17 | * Retrieves and returns the first element of the queue 18 | * @returns first element of the queue 19 | */ 20 | dequeue() { 21 | return this._queue.shift(); 22 | } 23 | 24 | /** 25 | * Returns the first item from the beginning of the queue 26 | * without deleting it 27 | * @returns first element of the queue 28 | */ 29 | peek() { 30 | return this._queue[0]; 31 | } 32 | 33 | /** 34 | * Clears the queue 35 | */ 36 | empty() { 37 | this._queue = []; 38 | } 39 | 40 | /** 41 | * Check for queue emptiness 42 | * @returns true/false 43 | */ 44 | get isEmpty() { 45 | return !this._queue.length; 46 | } 47 | 48 | /** 49 | * Queue length 50 | * @returns length 51 | */ 52 | get length() { 53 | return this._queue.length; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /Data Structures/Queue/Queue_test.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | import ( 4 | "testing" 5 | 6 | "github.com/stretchr/testify/assert" 7 | ) 8 | 9 | func TestEnqueueAndLength(t *testing.T) { 10 | queue := Queue{} 11 | queue.Enqueue(1) 12 | assert.Equal(t, 1, queue.Length()) 13 | } 14 | 15 | func TestDequeue(t *testing.T) { 16 | queue := Queue{} 17 | queue.Enqueue(1) 18 | assert.Equal(t, 1, queue.Length()) 19 | _ = queue.Dequeue() 20 | assert.Equal(t, 0, queue.Length()) 21 | } 22 | 23 | func TestPeek(t *testing.T) { 24 | queue := Queue{} 25 | item := 1 26 | queue.Enqueue(item) 27 | assert.Equal(t, item, queue.Peek()) 28 | queue.Enqueue(100) 29 | assert.Equal(t, item, queue.Peek()) 30 | } 31 | 32 | func TestEmpty(t *testing.T) { 33 | queue := Queue{} 34 | queue.Enqueue(1) 35 | assert.Equal(t, 1, queue.Length()) 36 | assert.Equal(t, false, queue.IsEmpty()) 37 | queue.Empty() 38 | assert.Equal(t, true, queue.IsEmpty()) 39 | } 40 | -------------------------------------------------------------------------------- /Data Structures/Queue/queue.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //self referencing structure with one data element 5 | struct Node { 6 | int data; 7 | struct Node *next; 8 | }; 9 | 10 | // Aliasing for easier referencing 11 | typedef struct Node Node; 12 | 13 | /*-------------------------------------- Queue Functions -------------------------------------- */ 14 | /** Ideally these should go in a seperate Header file (ie. queue.h) along with the self referencing structure 15 | * 16 | * Note : Queue is a ADT which is also a derived DS from LinkedList 17 | * 18 | * Queue Functions 19 | * Create Node : create_node 20 | * Insert : enqueue (append to the end of Queue) 21 | * Delete : dequeue (remove the first node of the Queue) 22 | * Peek : peek (views the first element in the queue) 23 | * Display List : print_queue 24 | * 25 | */ 26 | 27 | // Creates a Node in Heap and returns a pointer 28 | Node * create_node(int data) { 29 | Node *new_node = malloc(1 * sizeof(Node)); 30 | new_node->data = data; 31 | new_node->next = NULL; 32 | 33 | return new_node; 34 | } 35 | 36 | // appends a node to the end of the Queue 37 | void enqueue(Node **front, int data) { 38 | if(*front == NULL) { 39 | *front = create_node(data); 40 | }else { 41 | Node *current = *front; 42 | 43 | while(current->next != NULL) { 44 | current = current->next; 45 | } 46 | 47 | current->next = create_node(data); 48 | } 49 | } 50 | 51 | // removes the first element in the queue 52 | void dequeue(Node **front) { // Can be modified to return the removed Node | int according to the usage 53 | if(*front == NULL) { 54 | printf("Dequeue Failed : Empty Queue!!\n"); 55 | return; 56 | } 57 | 58 | Node *current = *front; 59 | 60 | *front = current->next; 61 | 62 | int deleted = current->data; 63 | 64 | free(current); 65 | 66 | printf("Dequeued : %d\n", deleted); 67 | 68 | } 69 | 70 | //Takes a peek at the first elemen in the queue 71 | void peek(Node *head) { 72 | if(head == NULL) { 73 | printf("Empty Queue!!\n"); 74 | }else { 75 | printf("First Element of the Queue : %d\n", head->data); 76 | } 77 | } 78 | 79 | // Prints all the elements in the Queue 80 | void print_queue(Node *head) { 81 | if(head == NULL) { 82 | printf("Empty Queue!!\n"); 83 | return; 84 | } 85 | 86 | printf("["); 87 | 88 | while(head != NULL) { 89 | printf(" %d", head->data); 90 | 91 | if(head->next != NULL) printf(","); 92 | 93 | head = head->next; 94 | } 95 | 96 | printf(" ]\n"); 97 | } 98 | /* --------------------------------- End of Queue Functions ----------------------------------- */ 99 | 100 | int main() { 101 | Node *queue = NULL; // Pointer to the First Node of the Queue 102 | 103 | enqueue(&queue, 10); 104 | enqueue(&queue, 30); 105 | enqueue(&queue, 50); 106 | enqueue(&queue, 60); 107 | 108 | print_queue(queue); 109 | 110 | 111 | dequeue(&queue); 112 | dequeue(&queue); 113 | peek(queue); 114 | 115 | print_queue(queue); 116 | 117 | return 0; 118 | } -------------------------------------------------------------------------------- /Data Structures/Stack/Stack Using Java/Stack.java: -------------------------------------------------------------------------------- 1 | public class Stack { 2 | 3 | stackNode head; 4 | 5 | public boolean isEmpty(){ 6 | if(head == null){ 7 | return true; 8 | }else{ 9 | return false; 10 | } 11 | } 12 | 13 | public void push(char data){ 14 | stackNode newNode = new stackNode(data); 15 | 16 | if(head == null){ 17 | head = newNode; 18 | }else{ 19 | newNode.next = head; 20 | head = newNode; 21 | } 22 | 23 | } 24 | 25 | public void pop(){ 26 | 27 | head = head.next; 28 | 29 | } 30 | 31 | public char peek(){ 32 | 33 | return head.data; 34 | 35 | } 36 | 37 | public void display(){ 38 | 39 | stackNode currentNode = head; 40 | 41 | while(currentNode != null){ 42 | System.out.println(currentNode.data); 43 | 44 | currentNode = currentNode.next; 45 | } 46 | 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /Data Structures/Stack/Stack Using Java/stackNode.java: -------------------------------------------------------------------------------- 1 | public class stackNode { 2 | stackNode next; 3 | 4 | //define any type of data here 5 | char data; 6 | 7 | stackNode(char data){ 8 | this.data = data; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Data Structures/Stack/Stack.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | type Stack []string 6 | 7 | // isEmpty: check if stack is empty 8 | func (s *Stack) isEmpty() bool { 9 | return len(*s) == 0 10 | } 11 | 12 | // push a new value onto the stack 13 | func (s *Stack) push(str string) { 14 | *s = append(*s, str) 15 | } 16 | 17 | // Remove and return top element of stack. Return false if stack is empty. 18 | func (s *Stack) pop() (string, bool) { 19 | if s.isEmpty() { 20 | return "", false 21 | } else { 22 | index := len(*s) - 1 23 | element := (*s)[index] 24 | *s = (*s)[:index] 25 | return element, true 26 | } 27 | } 28 | 29 | func main() { 30 | var stack Stack // create a stack variable of type Stack 31 | 32 | stack.push("Apple") 33 | stack.push("Orange") 34 | stack.push("Grapes") 35 | stack.push("Watermelons") 36 | stack.push("Papaya") 37 | 38 | fmt.Println(stack) // Output :- [Apple Orange Grapes Watermelons Papaya] 39 | 40 | stack.pop() 41 | stack.pop() 42 | 43 | fmt.Println(stack) // Output :- [Apple Orange Grapes] 44 | } 45 | -------------------------------------------------------------------------------- /Data Structures/Stack/Stack.java: -------------------------------------------------------------------------------- 1 | class Stack { 2 | static final int MAX = 100; // Maximum size of Stack 3 | int top; 4 | int a[] = new int[MAX]; 5 | Stack() { top = -1; } 6 | 7 | boolean push(int x) { 8 | if (top >= (MAX - 1)) { 9 | System.out.println("Stack Overflow"); 10 | return false; 11 | } 12 | else { 13 | a[++top] = x; 14 | return true; 15 | } 16 | } 17 | 18 | int pop() { 19 | if (top < 0) { 20 | System.out.println("Stack Underflow"); 21 | return 0; 22 | } 23 | else { 24 | int x = a[top--]; 25 | return x; 26 | } 27 | } 28 | 29 | int peek() { 30 | if (top < 0) { 31 | System.out.println("Stack Underflow"); 32 | return 0; 33 | } 34 | else { 35 | int x = a[top]; 36 | return x; 37 | } 38 | } 39 | 40 | boolean isEmpty() { 41 | return (top < 0); 42 | } 43 | } 44 | 45 | // Driver code 46 | class Main { 47 | public static void main(String args[]) 48 | { 49 | Stack stk = new Stack(); 50 | stk.push(1); 51 | stk.push(2); 52 | stk.push(3); 53 | System.out.println("1, 2, 3 added to stack"); 54 | 55 | // Pop up Stack 56 | System.out.println(stk.pop() + " Popped from stack"); 57 | 58 | // Get the top values 59 | System.out.println(stk.peek() + " is the peek value"); 60 | 61 | // isEmpty 62 | if (stk.isEmpty()){ 63 | System.out.println("Empty"); 64 | } 65 | else { 66 | System.out.println("Not empty"); 67 | } 68 | } 69 | } -------------------------------------------------------------------------------- /Data Structures/Stack/stack.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | //self referencing structure with one data element 5 | struct Node { 6 | int data; 7 | struct Node *next; 8 | }; 9 | 10 | // Aliasing for easier referencing 11 | typedef struct Node Node; 12 | 13 | /*-------------------------------------- Stack Functions -------------------------------------- */ 14 | /** Ideally these should go in a seperate Header file (ie. stack.h) along with the self referencing structure 15 | * 16 | * Stack Functions 17 | * Create Node : create_node 18 | * Push : push (adds an item to the top of the stack) 19 | * Pop : pop (removes the topmost item from the stack) 20 | * Peek : peek (take a look at the topmost item without popping) 21 | * Display Stack : print_stack 22 | * 23 | */ 24 | 25 | Node * create_node(int data) { 26 | Node *new_node = malloc(1 * sizeof(Node)); 27 | 28 | new_node->data = data; 29 | new_node->next = NULL; 30 | 31 | return new_node; 32 | } 33 | 34 | 35 | // adds a Node to the top of the stack 36 | void push(Node **top, int data) { 37 | Node *new_node = create_node(data); 38 | 39 | if(*top != NULL) { 40 | new_node->next = *top; 41 | } 42 | 43 | *top = new_node; 44 | 45 | } 46 | 47 | // Pops the Top Node from the Stack 48 | int pop(Node **top) { 49 | if(*top == NULL) { 50 | printf("Popping Failed: Empty Stack !!\n"); 51 | return -1; 52 | } 53 | 54 | Node *popped = *top; 55 | 56 | *top = popped->next; 57 | 58 | int popped_int = popped->data; 59 | 60 | free(popped); 61 | 62 | printf("Successfully Popped : %d\n", popped_int); 63 | 64 | return popped_int; 65 | } 66 | 67 | // Prints all the elements in the Stack 68 | void print_stack(Node *top) { 69 | if(top == NULL) { 70 | printf("Empty Stack!!\n"); 71 | return; 72 | } 73 | 74 | printf("["); 75 | 76 | while(top != NULL) { 77 | printf(" %d", top->data); 78 | 79 | if(top->next != NULL) printf(","); 80 | 81 | top = top->next; 82 | } 83 | 84 | printf(" ]\n"); 85 | } 86 | 87 | //Prints the topmost item in the Stack 88 | void peek(Node *top) { 89 | if(top == NULL) { 90 | printf("Empty Stack!!\n"); 91 | }else { 92 | printf("First item of the Stack : %d\n", top->data); 93 | } 94 | } 95 | 96 | /* --------------------------------- End of Stack Functions ----------------------------------- */ 97 | 98 | int main() { 99 | Node *stack = NULL; 100 | 101 | push(&stack,10); 102 | push(&stack,20); 103 | push(&stack,50); 104 | 105 | pop(&stack); 106 | peek(stack); 107 | 108 | push(&stack,40); 109 | push(&stack,80); 110 | 111 | print_stack(stack); 112 | 113 | } -------------------------------------------------------------------------------- /Dynamic Programming/Fibonacci Series/Fibonacci.java: -------------------------------------------------------------------------------- 1 | class Fibonacci{ 2 | static long memo[]; 3 | 4 | static long fib(int n){ 5 | long result = 0; 6 | if(memo[n] != 0) return memo[n]; 7 | 8 | if(n == 1 || n == 2) result = 1; 9 | 10 | else result = fib(n-1) + fib(n-2); 11 | 12 | memo[n] = result; 13 | 14 | return result; 15 | } 16 | public static void main(String[] args) { 17 | int n = 50; 18 | memo = new long[n+1]; 19 | System.out.println(fib(n)); 20 | } 21 | } -------------------------------------------------------------------------------- /Dynamic Programming/Longest Palindrome Substring/LongestPalindromeSubstring.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class LongestPalindromeSubstring{ 4 | 5 | public static void main(String[] args) 6 | { 7 | String str = "TestStringeee"; 8 | System.out.print("\nLength is: " + longestPalSubstring(str)); 9 | } 10 | 11 | 12 | static void printSubStr(String str, int low, int high) 13 | { 14 | for (int i = low; i <= high; ++i) 15 | System.out.print(str.charAt(i)); 16 | } 17 | 18 | 19 | static int longestPalSubstring(String str) 20 | { 21 | 22 | int n = str.length(); 23 | 24 | int maxLength = 1, start = 0; 25 | 26 | 27 | for (int i = 0; i < str.length(); i++) { 28 | for (int j = i; j < str.length(); j++) { 29 | int flag = 1; 30 | 31 | 32 | for (int k = 0; k < (j - i + 1) / 2; k++) 33 | if (str.charAt(i + k) != str.charAt(j - k)) 34 | flag = 0; 35 | 36 | 37 | if (flag!=0 && (j - i + 1) > maxLength) { 38 | start = i; 39 | maxLength = j - i + 1; 40 | } 41 | } 42 | } 43 | 44 | System.out.print("Longest palindrome subString is: "); 45 | printSubStr(str, start, start + maxLength - 1); 46 | 47 | 48 | return maxLength; 49 | } 50 | 51 | } 52 | 53 | 54 | -------------------------------------------------------------------------------- /Greedy Algorithms/Knapsack/Fractional Knapsack/Fractional_Knapsack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | //Quick sort 5 | int partition(vector &prices,vector &amount, int left, int right) 6 | { 7 | int pivotIndex = left + (right - left) / 2; 8 | int pivotValue = prices[pivotIndex]; 9 | int i = left, j = right; 10 | int temp; 11 | while(i <= j) 12 | { 13 | while(prices[i] < pivotValue) 14 | { 15 | i++; 16 | } 17 | while(prices[j] > pivotValue) 18 | { 19 | j--; 20 | } 21 | if(i <= j) 22 | { 23 | temp = prices[i]; 24 | prices[i] = prices[j]; 25 | prices[j] = temp; 26 | 27 | temp = amount[i]; 28 | amount[i] = amount[j]; 29 | amount[j] = temp; 30 | 31 | i++; 32 | j--; 33 | } 34 | } 35 | return i; 36 | } 37 | 38 | void quicksort(vector &prices,vector &amount, int left, int right) 39 | { 40 | if(left < right) 41 | { 42 | int pivotIndex = partition(prices,amount, left, right); 43 | quicksort(prices,amount ,left, pivotIndex - 1); 44 | quicksort(prices,amount, pivotIndex, right); 45 | } 46 | } 47 | //finding the maximum profit 48 | int findprof(vector weight,vectorprice,int n) 49 | { 50 | int sum=0; 51 | quicksort(price,weight, 0, price.size() - 1); 52 | 53 | for(int i=0;iweight[i]) 60 | { 61 | n=n-weight[i]; 62 | sum=sum+ price[i]*weight[i]; 63 | } 64 | else 65 | { 66 | sum=sum+n*price[i]; 67 | n=0; 68 | } 69 | } 70 | return sum; 71 | } 72 | 73 | int main() 74 | { 75 | int n,m; 76 | cout<<"Maximum weight of sack:"; 77 | cin>>n; 78 | cout<<"Number of weights:"; 79 | cin>>m; 80 | vector weight; 81 | vector price; 82 | 83 | cout<<"Enter the weights:"; 84 | for(int i=0;i>c; 88 | weight.push_back(c); 89 | } 90 | cout<<"Enter the prices:"; 91 | for(int i=0;i>c; 95 | price.push_back(c); 96 | } 97 | 98 | 99 | 100 | //getting the unit price 101 | for(int i=0;i 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n1, n2; 7 | 8 | cout << "Enter two numbers: "; 9 | cin >> n1 >> n2; 10 | 11 | while(n1 != n2) 12 | { 13 | if(n1 > n2) 14 | n1 -= n2; 15 | else 16 | n2 -= n1; 17 | } 18 | 19 | cout << "HCF = " << n1; 20 | return 0; 21 | } -------------------------------------------------------------------------------- /Mathematical Algorithms/GCD/gcd.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int n1, n2; 7 | 8 | cout << "Enter two numbers: "; 9 | cin >> n1 >> n2; 10 | 11 | while(n1 != n2) 12 | { 13 | if(n1 > n2) 14 | n1 -= n2; 15 | else 16 | n2 -= n1; 17 | } 18 | 19 | cout << "HCF/GCD = " << n1; 20 | return 0; 21 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithm-Collection 2 | You can add following algorithms using any language to repo. please maintain the folder strcuture accordng to the following list structure. 3 | 4 | Ex: If you adding the **Hamilton Path** algorithm using java, the folder structure would be, 5 | 6 | ``` 7 | /BackTracking/HamiltonPath/ 8 | ``` 9 | 10 | and the file name would be **" HamiltonPath.java " or " HamiltonPath.txt "** 11 | 12 | ### List of Algorithms 13 | 14 | * [Breadth First Search](/BFS) 15 | * [Binary Search Tree](/BST) 16 | * [Backtracking](/BackTracking) 17 | * [Hamilton Path](/BackTracking/Hamilton%20Path) 18 | * [Knights Tour](/BackTracking/KnightsTour) 19 | * [NQueens](/BackTracking/NQueens) 20 | * [Rat In A Maze](/BackTracking/RatInAMaze) 21 | * [Sudoku Algorithm](/BackTracking/SudokuAlgorithm) 22 | * [Depth First Search](/DFS) 23 | * [Bit Manipulation](/BitManipulation) 24 | * [Checking Power of 2](/BitManipulation/Checking_power_of_2) 25 | * [Nth Magic No](/BitManipulation/Nth_magic_number) 26 | * [Set kth Bit](/BitManipulation/Set_kth_bit) 27 | * [Sparse Number](/BitManipulation/Sparse_number) 28 | * [Count Ones](/BitManipulation/count_ones) 29 | * [Divide Integers](/BitManipulation/divide_integers) 30 | * [Even Odd](/BitManipulation/even_odd) 31 | * [Print Subsets](/BitManipulation/print_subsets) 32 | * [Reverse Bits](/BitManipulation/reverse_bits) 33 | * [Single Number](/BitManipulation/single_number) 34 | * [Swap Bits](/BitManipulation/swap_bits) 35 | * [Data Structures](/Data%20Structures) 36 | * [Disjoint Set](/Data%20Structures/disjointset) 37 | * [Doubly Linked List](/Data%20Structures/DoublyLinkedList) 38 | * [Fenwick Tree](/Data%20Structures/Fenwick_tree) 39 | * [LCA](/Data%20Structures/LCA) 40 | * [Linked List](/Data%20Structures/Linked%20List) 41 | * [Queue](/Data%20Structures/Queue) 42 | * [Queue From Stack Or Stack From Queue](/Data%20Structures/QueueFromStack_StackFromQueue) 43 | * [Red Black Tree](/Data%20Structures/Red%20Black%20Tree) 44 | * [Singly Linked List](/Data%20Structures/SinglyLinkedList) 45 | * [Stack](/Data%20Structures/Stack) 46 | * [Segment Tree](/Data%20Structures/Segment%20Tree) 47 | * [Trie](/Data%20Structures/Trie) 48 | * [Dynamic Programming](/DP) 49 | * [Coin Change](/DP/Coin%20Change%20Problem) 50 | * [Collect Maximum Points](/DP/Collect_Max_Points) 51 | * [Edit Distance](/DP/EditDistance) 52 | * [Fibonacci Series](/DP/Fibonacci) 53 | * [Floyd Warshall Algorithm](/DP/Floyd%20Warshall%20Algorithm) 54 | * [Game Of Sum](/DP/game_of_sum) 55 | * [Knapsack](/DP/Knapsack) 56 | * [Longest Palindrome Substring](/DP/Longest%20Palindrome%20Substring) 57 | * [Longest Common Increasing Subsequence](/DP/LCIS) 58 | * [Longest Common Subsequence](/DP/LongestCommonSubsequence) 59 | * [Longest Increasing Subsequence](/DP/LongestIncreasingSubsequence) 60 | * [Longest Repeated Subsequence](/DP/Longest%20Repeated%20Subsequence) 61 | * [Matrix Chain Multiplication](/DP/MatrixChain_multiplication) 62 | * [Max Sum Increasing Subsequence](/DP/Maximum%20Sum%20Increasing%20Subsequence) 63 | * [Minimum Path Sum](/DP/MinimumPathSum) 64 | * [Number Of Islands](/DP/NumberOfIslands) 65 | * [Print Neatly](/DP/PrintNeatly) 66 | * [Shortest Uncommon Subsequence](/DP/ShortestUncommonSubsequence) 67 | * [Subset Sum](/DP/subset%20sum%20problem) 68 | * [Graph Algorithms](/Graph) 69 | * [Articulation Points](/Graph/Articulation_points) 70 | * [Bellman Ford SSSP](/Graph/BellmanFordSSSP) 71 | * [Bridges](/Graph/bridges) 72 | * [Centroid Decomposition](/Graph/Centroid%20Decomposition) 73 | * [Detect Cycle](/Graph/Detect_Cycle) 74 | * [Dials Algorithm](/Graph/DialsAlgorithm) 75 | * [Dijkstras SPT](/Graph/DijkstrasSPT) 76 | * [Euler Path](/Graph/EulerPath) 77 | * [Floyd Warshall](/Graph/FloydWarshall) 78 | * [Graph Coloring](/Graph/Graph_m_Coloring) 79 | * [Johnson's Algorithm](/Graph/Johnson'sAlgorithm) 80 | * [Kruskal MST](/Graph/KruskalsMST) 81 | * [Prims MST](/Graph/PrimsMST) 82 | * [Sack](/Graph/Sack) 83 | * [Targan SCC](/Graph/TarganSCC) 84 | * [Topo Sort](/Graph/TopoSort) 85 | * [Greedy Algorithms](/Greedy) 86 | * [Activity Selection](/Greedy/ActivitySelection) 87 | * [Containership](/Greedy/ContainerShip) 88 | * [Equalizing Bit Strings](/Greedy/EqualizingBitStrings) 89 | * [Gas Station](/Greedy/Gas%20Station) 90 | * [Greedy Graph Coloring](/Greedy/Greedy_Graph_Coloring) 91 | * [Huffman Coding](/Greedy/Huffman%20coding) 92 | * [Knapsack](/Greedy/Knapsack) 93 | * [Kruskal's Minimum Spanning Tree](/Greedy/Kruskal’sMinimumSpanningTree) 94 | * [Maximum Increasing Subarray](/Greedy/MaximumIncreasingSubarray) 95 | * [Minimum Coins](/Greedy/MinimumCoins) 96 | * [Odd Sum Subsequence](/Greedy/OddSumSubsequence) 97 | * [Hashing Algorithms](/Hashing) 98 | * [2 Sum](/Hashing/2_Sum) 99 | * [3 Sum](/Hashing/3_Sum) 100 | * [4 Sum](/Hashing/4_Sum) 101 | * [Mathematical Algorithms](/Math) 102 | * [3 Sum square complexity](/Math/3_Sum_square_complexity) 103 | * [Factors Of A Given Number](/Math/All%20factors%20of%20a%20given%20Number) 104 | * [Collatz Conjecture](/Math/collatz_conjecture) 105 | * [Combinations](/Math/Combinations) 106 | * [Convuxhull](/Math/convuxhull) 107 | * [Euler's Totient Function](/Math/eulers_totient_function) 108 | * [Factorization](/Math/Factorization) 109 | * [Factors](/Math/factors) 110 | * [Fast Exponentiation with Mod](/Math/Fast%20Exponentiation%20with%20Mod) 111 | * [Floor Square Root](/Math/floor_sqrt) 112 | * [Greatest Common Divisor](/Math/gcd) 113 | * [Histogram Area](/Math/histogram_area) 114 | * [Last Digit Exp](/Math/last_digit_exp) 115 | * [Logarithm](/Math/log) 116 | * [Lowest Common Multiple](/Math/lowest_common_multiple) 117 | * [Matrix Power](/Math/Matrix_Power) 118 | * [Max Divisible Number](/Math/max_divisible_num) 119 | * [Max Sub Rectangle](/Math/max_sub_rectangle) 120 | * [Max Sub Square](/Math/Max_Sub_Square) 121 | * [Miller Rabin Primality Test](/Math/miller_rabin_primality_test) 122 | * [Modular Multiplication Inverse](/Math/modular_multiplicative_inverse) 123 | * [Next Power of 2](/Math/NextPow2) 124 | * [Nth Root](/Math/nthRoot) 125 | * [Pascal Row](/Math/pascal_row) 126 | * [Power](/Math/Power) 127 | * [Prime](/Math/Prime) 128 | * [Randomized Algorithms](/Math/Randomized%20algorithms) 129 | * [Set](/Math/Set) 130 | * [Sieve Of Eratosthenes](/Math/sieve_of_eratosthenes) 131 | * [Square Root](/Math/squareroot) 132 | * [Subset Sum](/Math/subset_sum) 133 | * [Sum Of Digits](/Math/sum_of_digits) 134 | * [Tower Of Hanoi](/Math/TowerofHanoi) 135 | * [Truncated Square Root](/Math/truncated_square_root) 136 | * [Network Flow](/NetworkFlow) 137 | * [Dinic](/NetworkFlow/Dinic) 138 | * [Edmund Karp](/NetworkFlow/EdmundKarp) 139 | * [Ford Fulkerson](/NetworkFlow/FordFulkerson) 140 | * [Goldberg Tarjan](/NetworkFlow/GoldbergTarjan) 141 | * [Search Algorithms](/Search) 142 | * [Binary Search](/Search/BinarySearch) 143 | * [Fibonacci Search](/Search/FibonacciSearch) 144 | * [Hashing](/Search/hashing) 145 | * [Jump Search](/Search/JumpSearch) 146 | * [Linear Search](/Search/LinearSearch) 147 | * [Ternary Search](/Search/TernarySearch) 148 | * [Sorting Algorithms](/Sorting) 149 | * [Bubble Sort](/Sorting/bubble%20sort) 150 | * [Counting Sort](/Sorting/CountingSort) 151 | * [Heap Sort](/Sorting/HeapSort) 152 | * [Index Sort](/Sorting/IndexSort) 153 | * [Insertion Sort](/Sorting/InsertionSort) 154 | * [Merge Sort](/Sorting/MergeSort) 155 | * [Pancake Sorting](/Sorting/Pancake%20sorting) 156 | * [Quick Sort](/Sorting/QuickSort) 157 | * [Radix Sort](/Sorting/RadixSort) 158 | * [Selection Sort](/Sorting/SelectionSort) 159 | * [Shell Sort](/Sorting/ShellSort) 160 | * [String Algorithms](/String) 161 | * [Anagram](/String/Anagram) 162 | * [Balanced Parenthesis](/String/Balanced%20Parentheses) 163 | * [Hamming Distance](/String/Hamming%20distance) 164 | * [KMP](/String/KMP) 165 | * [Palindrome](/String/Palindrome) 166 | * [String Automaton](/String/String%20Automaton) 167 | * [String Matching](/String/String%20Matching) 168 | * [Substring](/String/Substring) 169 | * [Top K Frequent Words](/String/Top_K_Frequent_Words) 170 | * [Top K Frequent Words In Java](/String/top_k_frequent_words_in_java) 171 | * [Uncompressing Strings](/String/Uncompressing_Strings) 172 | -------------------------------------------------------------------------------- /Search Algorithms/Binary Search/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int BinarySearch(int array[],int sk,int size) 5 | { 6 | int flag=0,first=0,middle,x; 7 | int last=size-1; 8 | int position=-1; 9 | 10 | while(first<=last && flag==0) 11 | { 12 | middle=(first+last)/2; 13 | if(array[middle]==sk) 14 | { 15 | flag=1; 16 | position=middle; 17 | } 18 | else if(array[middle]>sk) 19 | last=middle-1; 20 | else 21 | first=middle+1; 22 | } 23 | 24 | return position; 25 | } 26 | 27 | int main() 28 | { 29 | 30 | int x,size,sk,result; 31 | 32 | printf("Enter the Size of the Array "); 33 | scanf("%d",&size); 34 | 35 | int array[size]; 36 | 37 | for(x=0;x= l) { 8 | int mid = l + (r - l) / 2; 9 | if (arr[mid] == value) 10 | return mid; 11 | if (arr[mid] > value) 12 | return binarySearch(arr, l, mid - 1, value); 13 | return binarySearch(arr, mid + 1, r, value); 14 | } 15 | return -1; 16 | } 17 | 18 | public static void main(String args[]) 19 | { 20 | Scanner sc = new Scanner(System.in); 21 | System.out.println("Enter the number you want to search:"); 22 | int value = sc.nextInt(); 23 | 24 | BinarySearch binarySearch = new BinarySearch(); 25 | int arr[] = { 2, 3, 4, 10, 40 }; 26 | int n = arr.length; 27 | int result = binarySearch.binarySearch(arr, 0, n - 1, value); 28 | if (result == -1) 29 | System.out.println("Not Found"); 30 | else 31 | System.out.println("Found at index :" + result); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /Search Algorithms/Breath First Search/bfs.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #define pb push_back 3 | 4 | using namespace std; 5 | 6 | vector v; 7 | vector> g; 8 | 9 | void edge(int a, int b) 10 | { 11 | g[a].pb(b); 12 | } 13 | 14 | void bfs(int u) 15 | { 16 | queue q; 17 | 18 | q.push(u); 19 | v[u] = true; 20 | 21 | while (!q.empty()) 22 | { 23 | 24 | int f = q.front(); 25 | q.pop(); 26 | 27 | cout << f << " "; 28 | 29 | for (auto i = g[f].begin(); i != g[f].end(); i++) 30 | { 31 | if (!v[*i]) 32 | { 33 | q.push(*i); 34 | v[*i] = true; 35 | } 36 | } 37 | } 38 | } 39 | 40 | int main() 41 | { 42 | int n, e; 43 | cin >> n >> e; 44 | 45 | v.assign(n, false); 46 | g.assign(n, vector()); 47 | 48 | int a, b; 49 | for (int i = 0; i < e; i++) 50 | { 51 | cin >> a >> b; 52 | edge(a, b); 53 | } 54 | 55 | for (int i = 0; i < n; i++) 56 | { 57 | if (!v[i]) 58 | bfs(i); 59 | } 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /Search Algorithms/Interpolation Search/InterpolationSearch.java: -------------------------------------------------------------------------------- 1 | import java.lang.Math ; 2 | 3 | public class Search { 4 | 5 | static int interpolation_search(int arr[],int key){ 6 | 7 | int start = 0 , end = arr.length -1 ; 8 | 9 | while(start <= end && key >= arr[start] && key <= arr[end]){ 10 | 11 | if(start == end){ 12 | if(arr[start] == key) return start ; 13 | return -1 ; 14 | } 15 | 16 | int pos = start + ((end - start) / (arr[end] - arr[start])*(key - arr[start])); 17 | 18 | if(arr[pos] == key) 19 | return pos ; 20 | if(arr[pos] < key) 21 | start = pos + 1 ; 22 | else 23 | end = pos - 1; 24 | } 25 | 26 | return -1 ; 27 | } 28 | 29 | 30 | 31 | 32 | public static void main(String ...s){ 33 | 34 | int arr[]= {1,3,5,7,9,13,19,30}; 35 | int key = 19; 36 | int index = interpolation_search(arr, key); 37 | System.out.println("-----INTERPOLATION SEARCH-----"); 38 | System.out.print("The key " + key + " "); 39 | System.out.print((index == -1) ? "doesn't exist in the Array." : ("is present at index: " + index)); 40 | 41 | } 42 | 43 | } -------------------------------------------------------------------------------- /Search Algorithms/Linear Search/Linear Search.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | int searchList( int list[], int numElems, int value){ 6 | 7 | int index = 0; 8 | int position = -1; 9 | bool found = false; 10 | 11 | while (index < numElems && !found) 12 | { 13 | if(list[index] == value) 14 | { 15 | found = true; 16 | position = index+1; 17 | } 18 | index++; 19 | } 20 | return position; 21 | } 22 | 23 | 24 | int main(){ 25 | 26 | int size=0; 27 | int key=0,i=0; 28 | int rest=0; 29 | 30 | printf("Enter size for the Array: "); 31 | scanf("%d",&size); 32 | 33 | if(size <= 0) { 34 | // To prevent buffer from overflowing and reading / writing out of defined bounds.. 35 | printf("Exiting : Array size cannot be smaller than 1\n"); 36 | exit(-1); 37 | } 38 | 39 | 40 | int *arr = malloc(size * sizeof(int)); // we should always define a variable size array on heap, because 41 | 42 | 43 | for(i=0;i 2 | 3 | void bubbleSort(int arr[], int n) 4 | { 5 | int i, j, temp; 6 | int swapped; 7 | for (i = 0; i < n-1; i++) 8 | { 9 | swapped = 0; 10 | for (j = 0; j < n-i-1; j++) 11 | { 12 | if (arr[j] > arr[j+1]) 13 | { 14 | temp = arr[i]; 15 | arr[i] = arr[j]; 16 | arr[j] = temp; 17 | swapped = 1; 18 | } 19 | } 20 | 21 | if (swapped == 0) 22 | break; 23 | } 24 | } 25 | 26 | void main() 27 | { 28 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 29 | int n = sizeof(arr)/sizeof(arr[0]); 30 | 31 | printf("Array before sort: \n"); 32 | for (int i=0; i < n; i++) 33 | printf("%d ", arr[i]); 34 | printf("\n\n"); 35 | 36 | bubbleSort(arr, n); 37 | 38 | printf("Sorted array: \n"); 39 | for (int i=0; i < n; i++) 40 | printf("%d ", arr[i]); 41 | printf("\n"); 42 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSortExample { 2 | static void bubbleSort(int[] arr) { 3 | int n = arr.length; 4 | int temp = 0; 5 | for(int i=0; i < n; i++){ 6 | for(int j=1; j < (n-i); j++){ 7 | if(arr[j-1] > arr[j]){ 8 | //swap elements 9 | temp = arr[j-1]; 10 | arr[j-1] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | 14 | } 15 | } 16 | 17 | } 18 | public static void main(String[] args) { 19 | int arr[] ={3,60,35,2,45,320,5}; 20 | 21 | System.out.println("Array Before Bubble Sort"); 22 | for(int i=0; i < arr.length; i++){ 23 | System.out.print(arr[i] + " "); 24 | } 25 | System.out.println(); 26 | 27 | bubbleSort(arr);//sorting array elements using bubble sort 28 | 29 | System.out.println("Array After Bubble Sort"); 30 | for(int i=0; i < arr.length; i++){ 31 | System.out.print(arr[i] + " "); 32 | } 33 | 34 | } 35 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort/BubbleSort.swift: -------------------------------------------------------------------------------- 1 | // 2 | // BubbleSort.swift 3 | // 4 | // 5 | // Created by Pubudu Mihiranga on 19/10/21. 6 | // 7 | 8 | import Foundation 9 | 10 | //MARK: - Bubble Sort algorithm 11 | 12 | func bubbleSort(_ dataArray: [Int]?) -> [Int] { 13 | 14 | //check if dataArray is nil 15 | guard var unsortedArray = dataArray else { 16 | fatalError("Bubble Sort failed") 17 | } 18 | 19 | //check if dataArray length is equal 1 20 | guard unsortedArray.count > 1 else { 21 | return unsortedArray 22 | } 23 | 24 | let lastPosition = unsortedArray.count - 1 25 | var shouldSwap = true 26 | 27 | while shouldSwap { 28 | shouldSwap = false 29 | for i in 1...lastPosition { 30 | if unsortedArray[i-1] > unsortedArray[i] { 31 | unsortedArray.swapAt(i-1, i) 32 | shouldSwap = true 33 | } 34 | } 35 | } 36 | 37 | return unsortedArray 38 | } 39 | 40 | //MARK: - Usage 41 | 42 | let dataArray1 = [3, 4, 5, 12, 0, 8, 1] 43 | print("Unsorted := \(dataArray1)") //output := Unsorted := [3, 4, 5, 1, 0, 8, 1] 44 | let sortedArray1 = bubbleSort(dataArray1) 45 | print("Sorted := \(sortedArray1)") //output := Sorted := [0, 1, 1, 3, 4, 5, 8] 46 | 47 | let dataArray2: [Int]? = nil 48 | print("Unsorted := \(dataArray2)") //output := Unsorted := nil 49 | let sortedArray2 = bubbleSort(dataArray2) 50 | print("Sorted := \(sortedArray2)") //output := Fatal error: Bubble Sort failed 51 | 52 | let dataArray3 = [5] 53 | print("Unsorted := \(dataArray3)") //output := Unsorted := [5] 54 | let sortedArray3 = bubbleSort(dataArray3) 55 | print("Sorted := \(sortedArray3)") //output := Sorted := [5] 56 | 57 | -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort/bubble sort.py: -------------------------------------------------------------------------------- 1 | # this function sorts a list in bubble sort algorithm 2 | def bubble_sort(lst): 3 | flag = True 4 | 5 | while flag : 6 | flag = False 7 | for i in range(len(lst)-1): 8 | if lst[i] > lst[i+1]: 9 | lst[i],lst[i+1] = lst[i+1],lst[i] 10 | flag = True 11 | 12 | 13 | lst = [1,5,2,7] # initialize the list which want to be sorted 14 | 15 | bubble_sort(lst) 16 | print(lst) # print the sorted list 17 | -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort/bubbleSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Bubble Sort 2 | class BubbleSort 3 | { 4 | void bubbleSort(int arr[]) 5 | { 6 | int n = arr.length; 7 | for (int i = 0; i < n-1; i++) 8 | for (int j = 0; j < n-i-1; j++) 9 | if (arr[j] > arr[j+1]) 10 | { 11 | // swap temp and arr[i] 12 | int temp = arr[j]; 13 | arr[j] = arr[j+1]; 14 | arr[j+1] = temp; 15 | } 16 | } 17 | 18 | /* Prints the array */ 19 | void printArray(int arr[]) 20 | { 21 | int n = arr.length; 22 | for (int i=0; i 2 | 3 | void bubbleSort(int array[], int size) { 4 | int temp = 0; 5 | for (int i = 0; i < size - 1; i++) { 6 | for (int j = 0; j < size - 1 - i; j++) { 7 | if (array[j] > array[j + 1]) { 8 | temp = array[j + 1]; 9 | array[j + 1] = array[j]; 10 | array[j] = temp; 11 | } 12 | } 13 | } 14 | } 15 | 16 | void printArray(int array[], int size) { 17 | std::cout << "array = [ "; 18 | for (int i = 0; i < size; i++) { 19 | std::cout << array[i] << " "; 20 | } 21 | std::cout << " ]" << std::endl; 22 | } 23 | 24 | int main() { 25 | int array[10] = {2,5,3,6,4,2,4,2,2,8}; 26 | 27 | printArray(array, 10); 28 | 29 | bubbleSort(array, 10); 30 | 31 | printArray(array, 10); 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Bubble Sort/bubble_sort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | var toBeSorted [10]int = [10]int{1,3,2,4,8,6,7,2,3,0} 8 | 9 | func bubbleSort(input [10]int) { 10 | 11 | n := 10 12 | 13 | swapped := true 14 | 15 | for swapped { 16 | 17 | swapped = false 18 | 19 | for i := 1; i < n; i++ { 20 | if input[i-1] > input[i] { 21 | fmt.Println("Swapping") 22 | 23 | input[i], input[i-1] = input[i-1], input[i] 24 | 25 | swapped = true 26 | } 27 | 28 | } 29 | } 30 | 31 | fmt.Println(input) 32 | } 33 | 34 | func main() { 35 | fmt.Println("Hello World") 36 | 37 | bubbleSort(toBeSorted) 38 | } 39 | -------------------------------------------------------------------------------- /Sorting Algorithms/Heap Sort/HeapSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void heapify(int arr[], int n, int i) 4 | { 5 | int temp; 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 | if (r < n && arr[r] > arr[largest]) 14 | largest = r; 15 | 16 | if (largest != i) 17 | { 18 | temp = arr[i]; 19 | arr[i] = arr[largest]; 20 | arr[largest] = temp; 21 | 22 | heapify(arr, n, largest); 23 | } 24 | } 25 | 26 | void heapSort(int arr[], int n) 27 | { 28 | int temp; 29 | 30 | for (int i = n / 2 - 1; i >= 0; i--) 31 | heapify(arr, n, i); 32 | 33 | for (int i=n-1; i>0; i--) 34 | { 35 | temp = arr[0]; 36 | arr[0] = arr[i]; 37 | arr[i] = temp; 38 | 39 | heapify(arr, i, 0); 40 | } 41 | } 42 | 43 | void main() 44 | { 45 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 46 | int n = sizeof(arr)/sizeof(arr[0]); 47 | 48 | printf("Array before sort: \n"); 49 | for (int i=0; i < n; i++) 50 | printf("%d ", arr[i]); 51 | printf("\n\n"); 52 | 53 | heapSort(arr, n); 54 | 55 | printf("Sorted array: \n"); 56 | for (int i=0; i < n; i++) 57 | printf("%d ", arr[i]); 58 | printf("\n"); 59 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Heap Sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | 2 | // Java program for implementation of Heap Sort 3 | public class HeapSort 4 | { 5 | public void sort(int arr[]) 6 | { 7 | int n = arr.length; 8 | 9 | // Build heap (rearrange array) 10 | for (int i = n / 2 - 1; i >= 0; i--) 11 | heapify(arr, n, i); 12 | 13 | // One by one extract an element from heap 14 | for (int i=n-1; i>0; i--) 15 | { 16 | // Move current root to end 17 | int temp = arr[0]; 18 | arr[0] = arr[i]; 19 | arr[i] = temp; 20 | 21 | // call max heapify on the reduced heap 22 | heapify(arr, i, 0); 23 | } 24 | } 25 | 26 | // To heapify a subtree rooted with node i which is 27 | // an index in arr[]. n is size of heap 28 | void heapify(int arr[], int n, int i) 29 | { 30 | int largest = i; // Initialize largest as root 31 | int l = 2*i + 1; // left = 2*i + 1 32 | int r = 2*i + 2; // right = 2*i + 2 33 | 34 | // If left child is larger than root 35 | if (l < n && arr[l] > arr[largest]) 36 | largest = l; 37 | 38 | // If right child is larger than largest so far 39 | if (r < n && arr[r] > arr[largest]) 40 | largest = r; 41 | 42 | // If largest is not root 43 | if (largest != i) 44 | { 45 | int swap = arr[i]; 46 | arr[i] = arr[largest]; 47 | arr[largest] = swap; 48 | 49 | // Recursively heapify the affected sub-tree 50 | heapify(arr, n, largest); 51 | } 52 | } 53 | 54 | /* A utility function to print array of size n */ 55 | static void printArray(int arr[]) 56 | { 57 | int n = arr.length; 58 | for (int i=0; i -1) && (arr[j] > max)) { 13 | arr[j + 1] = arr[j]; 14 | j--; 15 | } 16 | arr[j + 1] = max; 17 | 18 | } 19 | } 20 | 21 | public static void main(String[] args) { 22 | int[] ar = {56, 12, 32, 87, 65, 54, 43, 32, 31, 2}; 23 | System.out.println(Arrays.toString(ar)); 24 | insertionSort(ar); 25 | System.out.println(Arrays.toString(ar)); 26 | } 27 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Insertion Sort/InsertionSort.ts: -------------------------------------------------------------------------------- 1 | const insertionSort = (arr: Array) => { 2 | for (let i = 1; i < arr.length; i++) { 3 | let max = arr[i]; 4 | let j = i - 1; 5 | 6 | while ((j > -1) && (arr[j] > max)) { 7 | arr[j + 1] = arr[j]; 8 | j--; 9 | } 10 | arr[j + 1] = max; 11 | } 12 | }; 13 | 14 | const ar: number [] = [56, 12, 32, 87, 65, 54, 43, 32, 31, 2]; 15 | console.log(ar); 16 | insertionSort(ar); 17 | console.log(ar); -------------------------------------------------------------------------------- /Sorting Algorithms/Insertion Sort/insertion sort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void insertionSort(int array[]){ 4 | int i,j,key; 5 | int n=(int)(sizeof(array)/sizeof(int)); 6 | for(j=1;j<5;j++){ 7 | i=j-1; 8 | key=array[j]; 9 | while(i>=0&&array[i]>key){ 10 | array[i+1]=array[i]; 11 | i--; 12 | } 13 | array[i+1]=key; 14 | } 15 | 16 | } 17 | 18 | int main(){ 19 | int array[5]={50,20,10,40,30}; 20 | int i; 21 | insertionSort(&array); 22 | for( i=0;i<5;i++){ 23 | printf("%d ",array[i]); 24 | } 25 | return 0; 26 | } 27 | -------------------------------------------------------------------------------- /Sorting Algorithms/Quick Sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | class QuickSort { 2 | 3 | static void swap(int[] arr, int i, int j) { 4 | int temp = arr[i]; 5 | arr[i] = arr[j]; 6 | arr[j] = temp; 7 | } 8 | 9 | static int partition(int[] arr, int low, int high) { 10 | 11 | int pivot = arr[high]; 12 | int i = (low - 1); 13 | 14 | for (int j = low; j <= high - 1; j++) { 15 | if (arr[j] < pivot) { 16 | i++; 17 | swap(arr, i, j); 18 | } 19 | } 20 | swap(arr, i + 1, high); 21 | return (i + 1); 22 | } 23 | 24 | static void quickSort(int[] arr, int low, int high) { 25 | if (low < high) { 26 | int pi = partition(arr, low, high); 27 | quickSort(arr, low, pi - 1); 28 | quickSort(arr, pi + 1, high); 29 | } 30 | } 31 | 32 | static void printArray(int[] arr) { 33 | System.out.print("["); 34 | for (int j : arr) { 35 | System.out.print(j + ", "); 36 | } 37 | System.out.print("\b\b]"); 38 | } 39 | 40 | public static void main(String[] args) { 41 | int[] arr = {99, 1, 77, 66, 55, 44, 7, 22, 11, 3}; 42 | quickSort(arr, 0, arr.length - 1); 43 | printArray(arr); 44 | } 45 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Quick Sort/Quick_Sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int partition(vector &nums, int left, int right) 6 | { 7 | int pivotIndex = left + (right - left) / 2; 8 | int pivotValue = nums[pivotIndex]; 9 | int i = left, j = right; 10 | int temp; 11 | while(i <= j) 12 | { 13 | while(nums[i] < pivotValue) 14 | { 15 | i++; 16 | } 17 | while(nums[j] > pivotValue) 18 | { 19 | j--; 20 | } 21 | if(i <= j) 22 | { 23 | temp = nums[i]; 24 | nums[i] = nums[j]; 25 | nums[j] = temp; 26 | 27 | 28 | i++; 29 | j--; 30 | } 31 | } 32 | return i; 33 | } 34 | 35 | void quicksort(vector &nums, int left, int right) 36 | { 37 | if(left < right) 38 | { 39 | int pivotIndex = partition(nums, left, right); 40 | quicksort(nums,left, pivotIndex - 1); 41 | quicksort(nums,pivotIndex, right); 42 | } 43 | } 44 | 45 | 46 | int main(){ 47 | vector nums; 48 | 49 | nums.push_back(10); 50 | nums.push_back(30); 51 | nums.push_back(50); 52 | nums.push_back(60); 53 | nums.push_back(5); 54 | 55 | quicksort(nums,0, nums.size() - 1); 56 | 57 | for(int i=0; i < nums.size(); i++){ 58 | cout << nums.at(i) << ' '; 59 | } 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /Sorting Algorithms/Radix Sort/RadixSort.java: -------------------------------------------------------------------------------- 1 | // Radix sort Java implementation 2 | import java.io.*; 3 | import java.util.*; 4 | 5 | class RadixSort { 6 | 7 | // A utility function to get maximum value in arr[] 8 | static int getMaxValue(int arr[], int n) 9 | { 10 | int max = arr[0]; 11 | for (int i = 1; i < n; i++) 12 | if (arr[i] > max) 13 | max = arr[i]; 14 | return max; 15 | } 16 | 17 | // A function to do counting sort of arr[] according to 18 | // the digit represented by exp. 19 | static void countSort(int arr[], int n, int exp) 20 | { 21 | int output[] = new int[n]; // output array 22 | int i; 23 | int count[] = new int[10]; 24 | Arrays.fill(count, 0); 25 | 26 | // Store count of occurrences in count[] 27 | for (i = 0; i < n; i++) 28 | count[(arr[i] / exp) % 10]++; 29 | 30 | // Change count[i] so that count[i] now contains 31 | // actual position of this digit in output[] 32 | for (i = 1; i < 10; i++) 33 | count[i] += count[i - 1]; 34 | 35 | // Build the output array 36 | for (i = n - 1; i >= 0; i--) { 37 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 38 | count[(arr[i] / exp) % 10]--; 39 | } 40 | 41 | // Copy the output array to arr[], so that arr[] now 42 | // contains sorted numbers according to current digit 43 | for (i = 0; i < n; i++) 44 | arr[i] = output[i]; 45 | } 46 | 47 | // The main function to that sorts arr[] of size n using 48 | // Radix Sort 49 | static void radixsort(int arr[], int n) 50 | { 51 | // Find the maximum number to know number of digits 52 | int m = getMaxValue(arr, n); 53 | 54 | // Do counting sort for every digit. Note that 55 | // instead of passing digit number, exp is passed. 56 | // exp is 10^i where i is current digit number 57 | for (int exp = 1; m / exp > 0; exp *= 10) 58 | countSort(arr, n, exp); 59 | } 60 | 61 | /* A utility function to print an array */ 62 | static void displayArr(int arr[], int n) 63 | { 64 | for (int i = 0; i < n; i++) 65 | System.out.print(arr[i] + " "); 66 | System.out.println(); 67 | } 68 | 69 | /*Driver Method*/ 70 | public static void main(String[] args) 71 | { 72 | int arr[] = { 234, 12, 2, 99, 223, 34, 78, 434 }; 73 | int n = arr.length; 74 | 75 | System.out.println("Array before sorting: "); 76 | displayArr(arr,n); 77 | 78 | radixsort(arr, n); 79 | System.out.println("Array after sorting: "); 80 | displayArr(arr, n); 81 | } 82 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Selection sort/SelectionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void selectionSort(int arr[], int n) 4 | { 5 | for (int i = 0; i < n-1; i++) 6 | { 7 | int index = i; 8 | for (int j = i+1; j < n; j++) 9 | if (arr[j] < arr[index]) 10 | index = j; 11 | 12 | int temp = arr[index]; 13 | arr[index] = arr[i]; 14 | arr[i] = temp; 15 | } 16 | } 17 | 18 | void main() 19 | { 20 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 21 | int n = sizeof(arr)/sizeof(arr[0]); 22 | 23 | printf("Array before sort: \n"); 24 | for (int i=0; i < n; i++) 25 | printf("%d ", arr[i]); 26 | printf("\n\n"); 27 | 28 | selectionSort(arr, n); 29 | 30 | printf("Sorted array: \n"); 31 | for (int i=0; i < n; i++) 32 | printf("%d ", arr[i]); 33 | printf("\n"); 34 | } -------------------------------------------------------------------------------- /Sorting Algorithms/Selection sort/SelectionSort.class: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/gcsrilanka/Algorithm-Collection/5beeaa91b82f4a70aed0047fb3deb9d3bb340013/Sorting Algorithms/Selection sort/SelectionSort.class -------------------------------------------------------------------------------- /Sorting Algorithms/Selection sort/SelectionSort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | sampleData := []int{3, 4, 5, 2, 1, 7, 8, -1, -3} 7 | 8 | fmt.Println("\nUnsorted") 9 | fmt.Println(sampleData) 10 | 11 | selectionSort(sampleData) 12 | } 13 | 14 | func selectionSort(array []int) { 15 | length := len(array) 16 | for i := 0; i < length-1; i++ { 17 | minIndex := i 18 | for j := i + 1; j < length; j++ { 19 | if array[j] < array[minIndex] { 20 | array[j], array[minIndex] = array[minIndex], array[j] 21 | } 22 | } 23 | } 24 | 25 | fmt.Println("\nSorted") 26 | fmt.Println(array) 27 | } 28 | -------------------------------------------------------------------------------- /Sorting Algorithms/Selection sort/SelectionSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Selection Sort 2 | class SelectionSort 3 | { 4 | void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | 8 | // One by one move boundary of unsorted subarray 9 | for (int i = 0; i < n-1; i++) 10 | { 11 | // Find the minimum element in unsorted array 12 | int min_idx = i; 13 | for (int j = i+1; j < n; j++) 14 | if (arr[j] < arr[min_idx]) 15 | min_idx = j; 16 | 17 | // Swap the found minimum element with the first 18 | // element 19 | int temp = arr[min_idx]; 20 | arr[min_idx] = arr[i]; 21 | arr[i] = temp; 22 | } 23 | } 24 | 25 | // Prints the array 26 | void printArray(int arr[]) 27 | { 28 | int n = arr.length; 29 | for (int i=0; i 0; gap /= 2) 20 | { 21 | // Do a gapped insertion sort for this gap size. 22 | // The first gap elements a[0..gap-1] are already 23 | // in gapped order keep adding one more element 24 | // until the entire array is gap sorted 25 | for (int i = gap; i < n; i += 1) 26 | { 27 | // add a[i] to the elements that have been gap 28 | // sorted save a[i] in temp and make a hole at 29 | // position i 30 | int temp = arr[i]; 31 | 32 | // shift earlier gap-sorted elements up until 33 | // the correct location for a[i] is found 34 | int j; 35 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) 36 | arr[j] = arr[j - gap]; 37 | 38 | // put temp (the original a[i]) in its correct 39 | // location 40 | arr[j] = temp; 41 | } 42 | } 43 | return 0; 44 | } 45 | 46 | // Driver method 47 | public static void main(String args[]) 48 | { 49 | int arr[] = {12, 34, 54, 2, 3}; 50 | System.out.println("Array before sorting: "); 51 | displayArr(arr); 52 | 53 | ShellSort ss = new ShellSort(); 54 | ss.sort(arr); 55 | 56 | System.out.println("Array after sorting: "); 57 | displayArr(arr); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /String Algorithms/KMP/kmp.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | typedef int bool; 5 | #define TRUE 1 6 | #define FALSE 0 7 | 8 | void prefixArray(char *p, int*array); 9 | 10 | int kmpsearch(char*p, char*t){ 11 | const int M = strlen(p), N = strlen(t); // M - size of the pattern N - size of the test 12 | int array[M]; 13 | 14 | prefixArray(p, array); 15 | int q = 0; 16 | bool isFound = FALSE; 17 | 18 | for(int i = 0; i < N; i++){ 19 | 20 | while(q > 0 && p[q] != t[i]){ 21 | q = array[q-1]; 22 | } 23 | if(p[q] == t[i]){ 24 | q++; 25 | } 26 | 27 | if(q == M){ 28 | isFound = TRUE; 29 | printf("Valid shift at %d\n", i - M); 30 | q = array[q-1]; 31 | } 32 | } 33 | return isFound; 34 | } 35 | 36 | void prefixArray(char * p, int *array){ 37 | const int M = strlen(p); 38 | array[0] = 0; 39 | int k = 0; 40 | for(int i = 1; i < M; i++){ 41 | while(k > 0 && p[k] != p[i]){ 42 | k = array[k-1]; 43 | } 44 | if(p[k] == p[i]){ 45 | k++; 46 | } 47 | array[i] = k; 48 | } 49 | 50 | } 51 | 52 | 53 | void main(){ 54 | // char * p = "xyyxxyyxyy"; 55 | char * p = "abcdabd"; 56 | // char * t = "xycxyyxxyyxyyxxyyxyy"; 57 | char * t = "abc abcdab abcdabcdabde"; 58 | if(!kmpsearch(p, t)) printf("No valid shift found\n"); 59 | } -------------------------------------------------------------------------------- /String Algorithms/Palindrome/Palindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Palindrome { 4 | 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | 8 | String original, reverse = ""; // stores user entered value and it's reverse value 9 | 10 | System.out.println("Enter a string: "); 11 | original = sc.nextLine(); 12 | 13 | int length = original.length(); 14 | 15 | // reverse the original user input value 16 | for ( int i = length - 1; i >= 0; i-- ) { 17 | reverse = reverse + original.charAt(i); 18 | } 19 | 20 | // check equality of original value and reverse value 21 | if (original.equals(reverse)) { 22 | System.out.println(original + " is a palindrome string."); 23 | } 24 | else { 25 | System.out.println(original + " isn't a palindrome string."); 26 | } 27 | 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /String Algorithms/Palindrome/palindrome.js: -------------------------------------------------------------------------------- 1 | const isPalindrome = (string) => { 2 | 3 | const newString = string.split('').reverse().join(''); 4 | 5 | if (string !== newString) { 6 | console.log("not a palindrome"); 7 | } 8 | 9 | console.log("palindrome"); 10 | 11 | }; 12 | 13 | isPalindrome("NITIN"); --------------------------------------------------------------------------------