├── .gitignore ├── Bit manipulation └── Brian-kerningam's-algorithm.cpp ├── Bitmasking ├── 1. Unique number I.txt ├── 10. Unique Number III.txt ├── 11. Fast Exponentiation.txt ├── 12. generate subsets.txt ├── 13. codechef problem.txt ├── 2. get ith bit.txt ├── 2. set ith bit.txt ├── 3. clear ith bit.txt ├── 4. update ith bit by value(0 or 1).txt ├── 5. clear last i bits of a number.txt ├── 6. clear bits from ith index to jth (from right to left).txt ├── 7. Replace bits in N by M.txt ├── 8. Convert Decimal to Binary.txt └── 9. Unique Number II.txt ├── Graph ├── Adjancency_List_Representation.cpp ├── BFS.cpp ├── DFS.cpp ├── Graph.py └── README.md ├── README.md ├── Tree ├── Sorted_to_BST.cpp ├── Tree_traversal.cpp └── tree_vertical_order_print ├── banker's algo └── banker_algo_implementation.txt ├── basic_algo ├── Bucket sort ├── Cycle Sort ├── bubble_sort.py ├── cycle_sort.cpp ├── heapSort.cpp ├── insertion_sort.py ├── mergeSort.cpp ├── mergesort.py ├── quickSort.cpp ├── radix-sort.cpp └── selection_sort.py ├── machine-learning ├── knn.py └── linear_regression.py ├── recursion ├── README.md ├── Sudoku.cpp └── factorial.py └── searching ├── binary-search.py └── linear-search.py /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store -------------------------------------------------------------------------------- /Bit manipulation/Brian-kerningam's-algorithm.cpp: -------------------------------------------------------------------------------- 1 | // program to calculate number of set bits in binary representation of a an unsigned int. 2 | 3 | // time compexity : O(no. of set bits in binary representation of a number) 4 | // auxilliary space : O(1) 5 | 6 | #include 7 | using namespace std; 8 | 9 | int countBits(unsigned int n) 10 | { 11 | int res = 0; 12 | while(n>0) 13 | { 14 | n = (n & (n-1)); 15 | res++; 16 | } 17 | return res; 18 | } 19 | 20 | int main() 21 | { 22 | unsigned int n; 23 | cin >> n; 24 | cout << countBits(n); 25 | return 0; 26 | 27 | } -------------------------------------------------------------------------------- /Bitmasking/1. Unique number I.txt: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | /* 5 | Every number occurs twice in the array except one number 6 | find out that number 7 | */ 8 | 9 | int uniqueNumber(int ar[], int n) 10 | { 11 | int ans = 0; 12 | for(int i=0; i 2 | using namespace std; 3 | 4 | /* 5 | Every number is occuring thrice in the given array except one. find the unique number 6 | */ 7 | 8 | int main() 9 | { 10 | int count[64] = {0}; 11 | 12 | int n; 13 | cin>>n; 14 | int no; 15 | for(int i=0; i>no; 18 | //we will keep adding the bits of upcoming numbers in the count array 19 | 20 | int j=0; 21 | while(no>0) 22 | { 23 | count[j]+= (no&1); 24 | j++; 25 | no = no>>1; 26 | } 27 | } 28 | 29 | //now lets take mod with 3 of numbers present in the count array 30 | int ans = 0; 31 | int p = 1; 32 | for(int i=0; i 2 | using namespace std; 3 | 4 | int fastExponentiation(int a, int n) 5 | { 6 | int ans = 1; 7 | 8 | while(n>0) 9 | { 10 | if((n&1)==1) 11 | { 12 | ans*=a; 13 | } 14 | n>>=1; 15 | a*=a; 16 | } 17 | return ans; 18 | } 19 | 20 | int main() 21 | { 22 | 23 | int a,n; 24 | cin>>a>>n; 25 | cout< 2 | using namespace std; 3 | 4 | void filterChars(char c[], int n) 5 | { 6 | int j=0; 7 | while(n>0) 8 | { 9 | if(n&1) 10 | { 11 | cout<>=1; 15 | } 16 | cout<>c; 32 | printSubsequences(c); 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Bitmasking/13. codechef problem.txt: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); 5 | #define endl "\n" 6 | #define int long long 7 | 8 | /* 9 | problem link: 10 | https://www.codechef.com/COOK128B/problems/OROFAND 11 | */ 12 | 13 | int32_t main() 14 | { 15 | IOS; 16 | int t; 17 | cin>>t; 18 | while(t--) 19 | { 20 | int n,q; 21 | cin>>n>>q; 22 | 23 | int arr[n]; 24 | for(int i=0; i>arr[i]; 27 | } 28 | 29 | int bit[32] = {0}; 30 | for(int i=0; i0) 42 | { 43 | ans+=(1<>x>>v; 53 | x--; 54 | 55 | for(int i=0; i<32; i++) 56 | { 57 | if(((1<0) 72 | { 73 | ans+=(1< 2 | using namespace std; 3 | 4 | //task is to find ith bit (i starting from zero and from right side) in a number 5 | 6 | int ithBit(int n, int i) 7 | { 8 | int mask = 1< 0 ? 1 : 0; 10 | 11 | return bit; 12 | } 13 | 14 | int main() 15 | { 16 | int n,i; 17 | cin>>n>>i; 18 | cout< 2 | using namespace std; 3 | 4 | int setIthBit(int n, int i) 5 | { 6 | int mask = 1<>n>>i; 16 | cout< 2 | using namespace std; 3 | 4 | int clearIthBit(int n, int i) 5 | { 6 | int mask = ~(1<>n>>i; 16 | cout< 2 | using namespace std; 3 | 4 | int updateIthBitByValue(int n, int i, int v) 5 | { 6 | //lets first cleat ith bit 7 | int mask = (~(1<>n>>i>>v; 20 | 21 | cout< 2 | using namespace std; 3 | 4 | int clearLastIBits(int n, int i) 5 | { 6 | //lets take mask with all ones 7 | int mask = -1; 8 | 9 | //lets clear last i bits of our mask 10 | mask = (mask<>n>>i; 22 | cout< 2 | using namespace std; 3 | 4 | int clearBitsFromItoJ(int n, int i, int j) 5 | { 6 | //lets take one mask (a) as all ones with j+1 number of trailing zeros 7 | int a = (~0)<<(j+1); 8 | 9 | //lets take mask (b) as all zero with i number of trailing ones 10 | int b = (1<>n>>i>>j; 24 | cout< 2 | using namespace std; 3 | 4 | int replaceNbitsByMFromItoJ(int n, int m, int i, int j) 5 | { 6 | //lets first clear the bits in n from i to j 7 | int a = (~0)<<(j+1); 8 | 9 | int b = (1< 2 | using namespace std; 3 | 4 | int convertToBinary(int n) 5 | { 6 | //we will convert the n into is base 10 representation which will look like binary representation of n 7 | 8 | int ans = 0; 9 | int p = 1; 10 | 11 | while(n>0) 12 | { 13 | int last_bit = (n&1); 14 | ans+= p*last_bit; 15 | p*=10; 16 | n=(n>>1); 17 | } 18 | return ans; 19 | } 20 | 21 | int main() 22 | { 23 | int n; 24 | cin>>n; 25 | cout< 2 | using namespace std; 3 | 4 | /* 5 | We are given an array containg n numbers. All the numbers are present twice except for two numbers which are present only once. 6 | Find the unique numbers in linear time without using any extra space. ( Hint - Use Bitwise ) 7 | */ 8 | 9 | 10 | void uniqueNumberII(int n, int a[]) 11 | { 12 | int xo = 0; 13 | for(int i=0; i>1; 28 | } 29 | 30 | //now we will check, out of all numbers in array which numbers have set bit at position pos 31 | int mask = 1<0) 37 | { 38 | x = x^a[i]; 39 | } 40 | } 41 | //here we have our first unique number x 42 | 43 | //if we xor our unique number with the xor value of whole array then we will get our second unique number 44 | 45 | y = x^xo; 46 | 47 | cout<>n; 54 | int arr[n]; 55 | for(int i=0; i>arr[i]; 58 | } 59 | uniqueNumberII(n,arr); 60 | return 0; 61 | } -------------------------------------------------------------------------------- /Graph/Adjancency_List_Representation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | class Graph 4 | { 5 | int V; 6 | list *l; 7 | public: 8 | Graph(int v) 9 | { 10 | V=v; 11 | l=new list[V]; 12 | } 13 | void addEdge(int i,int j,bool undir=true) 14 | { 15 | l[i].push_back(j); 16 | if(undir){ 17 | l[j].push_back(i); 18 | } 19 | } 20 | void printGraph() 21 | { 22 | for(int i=0;i"; 26 | for(auto node:l[i]){ 27 | cout< 3 | using namespace std; 4 | class Graph{ 5 | int V; 6 | list *l; 7 | public: 8 | Graph(int v) 9 | { 10 | V=v; 11 | l=new list[v]; 12 | } 13 | void addEdge(int u,int v,bool undir=true) 14 | { 15 | l[u].push_back(v); 16 | if(undir) 17 | { 18 | l[v].push_back(u); 19 | } 20 | } 21 | void printGraph() 22 | { 23 | for(int i=0;i "; 26 | for(auto connected:l[i]) 27 | { 28 | cout< q; 36 | // Enqueuing Source to the Queue. 37 | q.push(source); 38 | 39 | bool *visited=new bool[V]{0}; 40 | 41 | // visited array to get info about visited vertices. 42 | 43 | visited[source]=true; 44 | 45 | while(!q.empty()) 46 | { 47 | int vertice=q.front(); 48 | q.pop(); 49 | cout< q; 68 | // Enqueuing Source to the Queue. 69 | q.push(src); 70 | 71 | bool *visited=new bool[V]{0}; 72 | int *parent=new int[V]; 73 | int *distance=new int[V]; 74 | parent[src]=src; 75 | distance[src]=0; 76 | // visited array to get info about visited vertices. 77 | 78 | visited[src]=true; 79 | 80 | while(!q.empty()) 81 | { 82 | int vertice=q.front(); 83 | q.pop(); 84 | for(auto neighbours:l[vertice]) 85 | { 86 | // Checking for every neighbour node it is visited or not. 87 | if(!visited[neighbours]){ 88 | 89 | q.push(neighbours); 90 | // Marked Visited. 91 | parent[neighbours]=vertice; 92 | distance[neighbours]=distance[vertice]+1; 93 | visited[neighbours]=true; 94 | } 95 | 96 | } 97 | } 98 | // Shortest distance of every Node from source. 99 | cout< 2 | using namespace std; 3 | class Graph 4 | { 5 | int V; 6 | list *l; 7 | public: 8 | Graph(int v) 9 | { 10 | V=v; 11 | l=new list[V]; 12 | } 13 | void addEdge(int u,int v,bool undir=true) 14 | { 15 | l[u].push_back(v); 16 | if(undir) 17 | { 18 | l[v].push_back(u); 19 | } 20 | } 21 | void dfshelper(int node,bool *visited) 22 | { 23 | visited[node]=true; 24 | cout< "; 44 | for(auto connected:l[i]) 45 | { 46 | cout< None : 8 | self.vertices = vertices 9 | self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)] 10 | 11 | 12 | # function to add an edge into the graph 13 | def addEdge(self, u, v) -> None : 14 | self.graph[u][v] = 1 15 | self.graph[v][u] = 1 16 | 17 | 18 | # function check if an edge exists between two edges 19 | def edgeExists(self, u, v) -> bool : 20 | return self.graph[u][v] == 1 and self.graph[v][u] == 1 21 | 22 | 23 | # function to remove an edge from the graph 24 | def removeEdge(self, u, v) -> None : 25 | if self.edgeExists(u, v) : 26 | self.graph[u][v] = 0 27 | self.graph[v][u] = 0 28 | 29 | 30 | # function to get the bfs traversal of the graph 31 | def bfsTraversal(self, source) -> None : 32 | visited = [False] * self.vertices 33 | visited[source] = True 34 | queue = list() 35 | queue.append(source) 36 | 37 | while queue : 38 | node = queue.pop(0) 39 | print(node, end = " ") 40 | 41 | for i in range(self.vertices) : 42 | if self.graph[node][i] == 1 and visited[i] is False : 43 | queue.append(i) 44 | visited[i] = True 45 | 46 | 47 | # function to get the depth first traversal of the graph 48 | def dfsTraversal(self, source, visited) -> None : 49 | visited[source] = True 50 | print(source, end = " ") 51 | 52 | for i in range(self.vertices) : 53 | if self.graph[source][i] == 1 and visited[i] is False : 54 | self.dfsTraversal(i, visited) 55 | 56 | 57 | 58 | # function to print the graph 59 | def printGraph(self) -> None : 60 | for row in self.graph : 61 | print(row) 62 | 63 | 64 | def main() : 65 | # enter the number of vertices and edges 66 | vertices, edges = map(int, input().split()) 67 | 68 | graph = UndirectedGraph(vertices) 69 | 70 | for _ in range(edges) : 71 | u, v = map(int, input().split()) 72 | graph.addEdge(u, v) 73 | 74 | 75 | 76 | graph.bfsTraversal(1) 77 | print() 78 | visited = [False] * vertices 79 | graph.dfsTraversal(0, visited) 80 | 81 | 82 | 83 | if __name__ == '__main__' : 84 | main() 85 | -------------------------------------------------------------------------------- /Graph/README.md: -------------------------------------------------------------------------------- 1 | ## Example 2 | 3 | ![Adjacency List](https://i.imgur.com/JwA2sxn.png) 4 | 5 | ## DFS and BFS example. 6 | ![giphy](https://i.stack.imgur.com/7BcgD.png) 7 | 8 | 9 | Made with ❤️ by @Mithil G Anchan -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Algorithms 2 | This repository contains computer science algorithms code. 3 | 4 | ## Contribution Guidelines 5 | 6 | * Fork the algorithms Repository from Coding Minutes 7 | * Now from your Github account Clone the Repository 8 | * Add new algorithms from your working directory 9 | * commit the changes when your code is errorfree 10 | * push the code and click on contribute in your github (server) 11 | * Click on Create a pull Request 12 | * Done. 13 | 14 | If your Contribution is genuine it will get merged with main Repository (i.e algorithms) 15 | 16 | -------------------------------------------------------------------------------- /Tree/Sorted_to_BST.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | /* 8 | Given a sorted, we need to build a BST out of it. 9 | */ 10 | 11 | class Node{ 12 | public: 13 | int data; 14 | Node *left,*right; 15 | Node(int data){ 16 | this->data = data; 17 | left=right= NULL; 18 | } 19 | }; 20 | 21 | // Function to convert sorted array to BST 22 | Node* sortedToBST(vector num,int s,int e){ 23 | if(s > e){ 24 | return NULL; 25 | } 26 | int mid = (s+e)/2; 27 | Node* root = new Node(num[mid]); 28 | root->left = sortedToBST(num,s,mid-1); 29 | root->right = sortedToBST(num,mid+1,e); 30 | return root; 31 | } 32 | 33 | // Printing the level order traversal 34 | void LevelOrder(Node* root){ 35 | if(root == NULL){ 36 | return; 37 | } 38 | queue q; 39 | q.push(root); 40 | while(!q.empty()){ 41 | int n = q.size(); 42 | for(int i=0;idata << "->"; 46 | if(temp->left != NULL){ 47 | q.push(temp->left); 48 | } 49 | if(temp->right != NULL){ 50 | q.push(temp->right); 51 | } 52 | } 53 | } 54 | } 55 | 56 | int main(){ 57 | vector v = {1,2,3,4,5,6,7,8,9,10}; 58 | Node* root = sortedToBST(v,0,v.size()-1); 59 | LevelOrder(root); 60 | return 0; 61 | } 62 | 63 | // Output : 5->2->8->1->3->6->9->4->7->10-> 64 | /* 65 | 5 66 | / \ 67 | 2 8 68 | / \ / \ 69 | 1 3 6 9 70 | \ \ \ 71 | 4 7 10 72 | */ -------------------------------------------------------------------------------- /Tree/Tree_traversal.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | /* 7 | PreOrder = Printing node first then going left then right. 8 | InOrder = First going left, printing the node and then going right. 9 | PostOrder = First going left and right then printing the node. 10 | LevelOrder = Printing the nodes which are at same level. 11 | */ 12 | 13 | class Node{ 14 | public: 15 | int data; 16 | Node *left, *right; 17 | Node(int data){ 18 | this->data = data; 19 | left = right = NULL; 20 | } 21 | }; 22 | 23 | // Pre-order Traversal of Tree 24 | void PreOrder(Node* root){ 25 | if(root == NULL){ 26 | return; 27 | } 28 | 29 | cout << root->data << "->"; 30 | PreOrder(root->left); 31 | PreOrder(root->right); 32 | } 33 | 34 | // In-order Traversal of Tree 35 | void InOrder(Node* root){ 36 | if(root == NULL){ 37 | return; 38 | } 39 | 40 | InOrder(root->left); 41 | cout << root->data << "->"; 42 | InOrder(root->right); 43 | } 44 | 45 | // Post-Order Traversal Of Tree 46 | void PostOrder(Node* root){ 47 | if(root == NULL){ 48 | return; 49 | } 50 | 51 | PostOrder(root->left); 52 | PostOrder(root->right); 53 | cout << root->data << "->"; 54 | } 55 | 56 | // Level-Order Traversal of Tree 57 | void LevelOrder(Node* root){ 58 | if(root == NULL){ 59 | return; 60 | } 61 | queue q; 62 | q.push(root); 63 | while(!q.empty()){ 64 | int n = q.size(); 65 | for(int i=0;idata << "->"; 69 | if(temp->left != NULL){ 70 | q.push(temp->left); 71 | } 72 | if(temp->right != NULL){ 73 | q.push(temp->right); 74 | } 75 | } 76 | } 77 | } 78 | 79 | int main() { 80 | Node* root = new Node(1); 81 | root->left = new Node(12); 82 | root->right = new Node(9); 83 | root->left->left = new Node(5); 84 | root->left->right = new Node(6); 85 | root->right->left = new Node(8); 86 | root->right->right = new Node(15); 87 | 88 | /*-Tree structure 89 | 1 90 | / \ 91 | 12 9 92 | / \ / \ 93 | 5 6 8 15 94 | */ 95 | 96 | cout << "\nIn-Order traversal \n"; 97 | InOrder(root); 98 | // Output :- 5->12->6->1->8->9->15-> 99 | 100 | cout << "\nPre-Order Traversal \n"; 101 | PreOrder(root); 102 | // Output :- 1->12->5->6->9->8->15-> 103 | 104 | cout << "\nPost-Order Traversal \n"; 105 | PostOrder(root); 106 | // Output :- 5->6->12->8->15->9->1-> 107 | 108 | cout << "\nLevel-Order Traversal \n"; 109 | LevelOrder(root); 110 | // Output :- 1->12->9->5->6->8->15-> 111 | 112 | return 0; 113 | } -------------------------------------------------------------------------------- /Tree/tree_vertical_order_print: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node{ 5 | public: 6 | int data; 7 | node* left; 8 | node* right; 9 | node(int d){ 10 | data=d; 11 | left=NULL; 12 | right=NULL; 13 | } 14 | }; 15 | node * binary_tree(int dis,map>&m){ 16 | int d;cin>>d; 17 | if(d==-1){ 18 | return NULL; 19 | } 20 | node* tree=new node(d); 21 | m[dis].push_back(d); 22 | tree->left=binary_tree(dis-1,m); 23 | tree->right=binary_tree(dis+1,m); 24 | return tree; 25 | } 26 | void print(node *t){ 27 | if(t==NULL){ 28 | return; 29 | } 30 | cout<<(t->data)<<" "; 31 | print(t->left); 32 | print(t->right); 33 | } 34 | int main() { 35 | int dis=0; 36 | map>m; 37 | node *t=binary_tree(dis,m); 38 | print(t); 39 | cout< "; 42 | for(auto y:x.second){ 43 | cout< 2 | using namespace std; 3 | 4 | bool ek_bhi_mil_rha(vector>remaining_need, vectorcurrrently_available,vectordone_process){ 5 | int count=0; 6 | for(auto x:done_process){ 7 | if(x==0){ 8 | count++; 9 | } 10 | } 11 | for(int i=0;i currrently_available[j]){ 18 | flag=true; 19 | break; 20 | } 21 | } 22 | if(flag==true){ 23 | count--; 24 | } 25 | } 26 | if(count>0){ 27 | return true; 28 | } 29 | return false; 30 | } 31 | 32 | int main() { 33 | // input number of processes 34 | int number_of_process; 35 | cout<<"Enter Number of Processes:"<>number_of_process; 37 | // input number of resources 38 | int number_of_resources; 39 | cout<<"Enter Number of Resources:"<>number_of_resources; 41 | // input total instances of each resources 42 | int total_resources_count[number_of_resources]; 43 | cout<<"Enter Total instances of each resource:"<>a; 49 | total_resources_count[i]=a; 50 | } 51 | 52 | vector>allocation; 53 | vector>max_need; 54 | vectorcurrrently_available; 55 | vector>remaining_need; 56 | 57 | // fill allocation and max_need now 58 | temp=1; 59 | cout<<"Now, Enter Allocation and maximum need of each resource for each process: "<k; 63 | cout<<"Enter Allocation for process "<<(temp)<<" :"<>a; 67 | k.push_back(a); 68 | } 69 | allocation.push_back(k); 70 | // input for max_need 71 | vectorl; 72 | cout<<"Enter maximum need for process "<<(temp)<<" :"<>a; 76 | l.push_back(a); 77 | } 78 | max_need.push_back(l); 79 | temp++; 80 | } 81 | // remaining need 82 | 83 | for(int i=0;ik; 85 | for(int j=0;jdone_process(number_of_process,0); 105 | cout< currrently_available[j]){ 112 | flag=true; 113 | } 114 | } 115 | // if flag is true means that process can't be processed right now. 116 | if(flag==true){ 117 | continue; 118 | } 119 | // else if not true, means that process can be processed 120 | // lets complete that process 121 | if(done_process[i]==0){ 122 | done_process[i]=1; 123 | cout<<"completed process: "<<(i+1)< 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | 7 | void bucketSort(float arr[], int n) 8 | { 9 | 10 | // 1) Create n empty buckets 11 | vector b[n]; 12 | 13 | // 2) Put array elements 14 | // in different buckets 15 | for (int i = 0; i < n; i++) { 16 | int bi = n * arr[i]; // Index in bucket 17 | b[bi].push_back(arr[i]); 18 | } 19 | 20 | // 3) Sort individual buckets 21 | for (int i = 0; i < n; i++) 22 | sort(b[i].begin(), b[i].end()); 23 | 24 | // 4) Concatenate all buckets into arr[] 25 | int index = 0; 26 | for (int i = 0; i < n; i++) 27 | for (int j = 0; j < b[i].size(); j++) 28 | arr[index++] = b[i][j]; 29 | } 30 | 31 | /* Driver program to test above function */ 32 | int main() 33 | { 34 | float arr[] 35 | = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; 36 | int n = sizeof(arr) / sizeof(arr[0]); 37 | bucketSort(arr, n); 38 | 39 | cout << "Sorted array is \n"; 40 | for (int i = 0; i < n; i++) 41 | cout << arr[i] << " "; 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /basic_algo/Cycle Sort: -------------------------------------------------------------------------------- 1 | // C++ program to implement cycle sort 2 | #include 3 | using namespace std; 4 | 5 | // Function sort the array using Cycle sort 6 | void cycleSort(int arr[], int n) 7 | { 8 | // count number of memory writes 9 | int writes = 0; 10 | 11 | // traverse array elements and put it to on 12 | // the right place 13 | for (int cycle_start = 0; cycle_start <= n - 2; cycle_start++) { 14 | // initialize item as starting point 15 | int item = arr[cycle_start]; 16 | 17 | // Find position where we put the item. We basically 18 | // count all smaller elements on right side of item. 19 | int pos = cycle_start; 20 | for (int i = cycle_start + 1; i < n; i++) 21 | if (arr[i] < item) 22 | pos++; 23 | 24 | // If item is already in correct position 25 | if (pos == cycle_start) 26 | continue; 27 | 28 | // ignore all duplicate elements 29 | while (item == arr[pos]) 30 | pos += 1; 31 | 32 | // put the item to it's right position 33 | if (pos != cycle_start) { 34 | swap(item, arr[pos]); 35 | writes++; 36 | } 37 | 38 | // Rotate rest of the cycle 39 | while (pos != cycle_start) { 40 | pos = cycle_start; 41 | 42 | // Find position where we put the element 43 | for (int i = cycle_start + 1; i < n; i++) 44 | if (arr[i] < item) 45 | pos += 1; 46 | 47 | // ignore all duplicate elements 48 | while (item == arr[pos]) 49 | pos += 1; 50 | 51 | // put the item to it's right position 52 | if (item != arr[pos]) { 53 | swap(item, arr[pos]); 54 | writes++; 55 | } 56 | } 57 | } 58 | 59 | // Number of memory writes or swaps 60 | // cout << writes << endl ; 61 | } 62 | 63 | // Driver program to test above function 64 | int main() 65 | { 66 | int arr[] = { 1, 8, 3, 9, 10, 10, 2, 4 }; 67 | int n = sizeof(arr) / sizeof(arr[0]); 68 | cycleSort(arr, n); 69 | 70 | cout << "After sort : " << endl; 71 | for (int i = 0; i < n; i++) 72 | cout << arr[i] << " "; 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /basic_algo/bubble_sort.py: -------------------------------------------------------------------------------- 1 | 2 | value = [81, 24 , 4783, 38, -37, 10] 3 | 4 | def bubbleSort(arr): 5 | 6 | for i in range(len(arr)): 7 | 8 | for j in range(0, len(arr) - i - 1): 9 | if arr[j] > arr[j + 1]: 10 | 11 | temp = arr[j] 12 | arr[j] = arr[j+1] 13 | arr[j+1] = temp 14 | 15 | 16 | 17 | bubbleSort(value) 18 | print(value) -------------------------------------------------------------------------------- /basic_algo/cycle_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void sort(int a[], int n) 3 | { 4 | int writes = 0,start,element,pos,temp,i; 5 | 6 | for (start = 0; start <= n - 2; start++) { 7 | element = a[start]; 8 | pos = start; 9 | for (i = start + 1; i < n; i++) 10 | if (a[i] < element) 11 | pos++; 12 | if (pos == start) 13 | continue; 14 | while (element == a[pos]) 15 | pos += 1; 16 | if (pos != start) { 17 | //swap(element, a[pos]); 18 | temp = element; 19 | element = a[pos]; 20 | a[pos] = temp; 21 | writes++; 22 | } 23 | while (pos != start) { 24 | pos = start; 25 | for (i = start + 1; i < n; i++) 26 | if (a[i] < element) 27 | pos += 1; 28 | while (element == a[pos]) 29 | pos += 1; 30 | if (element != a[pos]) { 31 | temp = element; 32 | element = a[pos]; 33 | a[pos] = temp; 34 | writes++; 35 | } 36 | } 37 | } 38 | 39 | } 40 | 41 | int main() 42 | { 43 | int a[] = {1, 9, 2, 4, 2, 10, 45, 3, 2}; 44 | int n = sizeof(a) / sizeof(a[0]),i; 45 | sort(a, n); 46 | printf("After sort, array : "); 47 | for (i = 0; i < n; i++) 48 | printf("%d ",a[i]); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /basic_algo/heapSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void heapify(int arr[], int n, int i) { 5 | 6 | int left = (i * 2) + 1, right = (i * 2) + 2; 7 | int largest = i; 8 | 9 | if (left < n && arr[left] > arr[largest]) 10 | largest = left; 11 | if (right < n && arr[right] > arr[largest]) 12 | largest = right; 13 | 14 | if (largest != i) { 15 | swap(arr[i], arr[largest]); 16 | heapify(arr, n, largest); 17 | } 18 | } 19 | void buildHeap(int arr[], int n) { 20 | 21 | for (int i = (n - 2) / 2; i >= 0; i--) { 22 | heapify(arr, n, i); 23 | } 24 | } 25 | void heapSort(int arr[], int n) { 26 | buildHeap(arr, n); 27 | for (int i = n - 1; i > 0; i--) { 28 | swap(arr[0], arr[i]); 29 | heapify(arr, i, 0); 30 | } 31 | } 32 | int32_t main() 33 | { 34 | ios_base::sync_with_stdio(false); cin.tie(0); 35 | #ifndef ONLINE_JUDGE 36 | freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); 37 | #endif 38 | 39 | 40 | int n; 41 | cin >> n; 42 | int a[n]; 43 | 44 | for (int i = 0; i < n; i++) { 45 | cin >> a[i]; 46 | } 47 | 48 | heapSort(a, n); 49 | 50 | for (int i = 0; i < n; i++) 51 | cout << a[i] << " "; 52 | cout << endl; 53 | 54 | return 0; 55 | 56 | } 57 | 58 | -------------------------------------------------------------------------------- /basic_algo/insertion_sort.py: -------------------------------------------------------------------------------- 1 | 2 | value = [81, 24 , 4783, 38, -37, 10] 3 | 4 | def insertionSort(arr): 5 | 6 | for i in range(1, len(arr)): 7 | ins = arr[i] 8 | j = i - 1 9 | 10 | while j >= 0 and ins < arr[j]: 11 | arr[j + 1] = arr[j] 12 | j = j - 1 13 | 14 | arr[j + 1] = ins 15 | 16 | 17 | insertionSort(value) 18 | print(value) -------------------------------------------------------------------------------- /basic_algo/mergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge(vector &a, int s, int m, int e) { 5 | int temp[e]; 6 | int i = s, j = m + 1, k = s; 7 | while (i <= m and j <= e) { 8 | if (a[i] < a[j]) { 9 | temp[k++] = a[i++]; 10 | } else { 11 | temp[k++] = a[j++]; 12 | } 13 | } 14 | while (i <= m) { 15 | temp[k++] = a[i++]; 16 | } 17 | while (j <= e) { 18 | temp[k++] = a[j++]; 19 | } 20 | for (int i = s; i <= e; i++) { 21 | a[i] = temp[i]; 22 | } 23 | } 24 | void mergeSort(vector &a, int s, int e) { 25 | if (s >= e) 26 | return; 27 | int m = (s + e) / 2; 28 | mergeSort(a, s, m ); 29 | mergeSort(a, m + 1, e); 30 | merge(a, s, m, e); 31 | } 32 | 33 | int32_t main() 34 | { 35 | ios_base::sync_with_stdio(false); cin.tie(0); 36 | int n; 37 | cin >> n; 38 | vector a(n); 39 | for (int i = 0; i < n; i++) { 40 | cin >> a[i]; 41 | } 42 | mergeSort(a, 0, n - 1); 43 | for (int i = 0; i < n; i++) 44 | cout << a[i] << " "; 45 | cout << endl; 46 | 47 | return 0; 48 | 49 | } 50 | 51 | -------------------------------------------------------------------------------- /basic_algo/mergesort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i]), 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i]), 79 | 80 | # This code is contributed by Mohit Kumra 81 | -------------------------------------------------------------------------------- /basic_algo/quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int partition(vector &a, int s, int e) { 5 | int i = s - 1; 6 | int j = s; 7 | int pivot = a[e]; 8 | for (; j < e; j++) { 9 | if (a[j] <= pivot) { 10 | i++; 11 | swap(a[i], a[j]); 12 | } 13 | } 14 | swap(a[i + 1], a[e]); 15 | return i + 1; 16 | 17 | } 18 | 19 | void quickSort(vector &a, int s, int e) { 20 | if (s >= e) 21 | return; 22 | int p = partition(a, s, e); 23 | quickSort(a, s, p - 1); 24 | quickSort(a, p + 1, e); 25 | return; 26 | } 27 | 28 | int32_t main() 29 | { 30 | ios_base::sync_with_stdio(false); cin.tie(0); 31 | int n; 32 | cin >> n; 33 | 34 | vector a(n); 35 | for (int i = 0; i < n; i++) { 36 | cin >> a[i]; 37 | } 38 | 39 | quickSort(a, 0, n - 1); 40 | 41 | for (int i = 0; i < n; i++) 42 | cout << a[i] << " "; 43 | cout << endl; 44 | 45 | return 0; 46 | 47 | } 48 | -------------------------------------------------------------------------------- /basic_algo/radix-sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | // Get maximum value from array. 6 | int getMax(int arr[], int n) 7 | { 8 | int max = arr[0]; 9 | for (int i = 1; i < n; i++) 10 | if (arr[i] > max) 11 | max = arr[i]; 12 | return max; 13 | } 14 | 15 | // Count sort of arr[]. 16 | void countSort(int arr[], int n, int exp) 17 | { 18 | // Count[i] array will be counting the number of array values having that 'i' digit at their (exp)th place. 19 | int output[n], i, count[10] = {0}; 20 | 21 | // Count the number of times each digit occurred at (exp)th place in every input. 22 | for (i = 0; i < n; i++) 23 | count[(arr[i] / exp) % 10]++; 24 | 25 | // Calculating their cumulative count. 26 | for (i = 1; i < 10; i++) 27 | count[i] += count[i-1]; 28 | 29 | // Inserting values according to the digit '(arr[i] / exp) % 10' fetched into count[(arr[i] / exp) % 10]. 30 | for (i = n - 1; i >= 0; i--) 31 | { 32 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 33 | count[(arr[i] / exp) % 10]--; 34 | } 35 | 36 | // Assigning the result to the arr pointer of main(). 37 | for (i = 0; i < n; i++) 38 | arr[i] = output[i]; 39 | } 40 | 41 | // Sort arr[] of size n using Radix Sort. 42 | void radixsort(int arr[], int n) 43 | { 44 | int exp, m; 45 | m = getMax(arr, n); 46 | 47 | // Calling countSort() for digit at (exp)th place in every input. 48 | for (exp = 1; m/exp > 0; exp *= 10) 49 | countSort(arr, n, exp); 50 | } 51 | 52 | int main() 53 | { 54 | int n, i; 55 | cout<<"\nEnter the number of data element to be sorted: "; 56 | cin>>n; 57 | 58 | int arr[n]; 59 | for(i = 0; i < n; i++) 60 | { 61 | cout<<"Enter element "<>arr[i]; 63 | } 64 | 65 | radixsort(arr, n); 66 | 67 | // Printing the sorted data. 68 | cout<<"\nSorted Data "; 69 | for (i = 0; i < n; i++) 70 | cout<<"->"< 2 | using namespace std; 3 | bool isSafe(int mat[][9],int i,int j,int n,int no) 4 | { 5 | for(int k=0;k 0: 19 | print("Element found at", pos) 20 | else: 21 | print("Element not found") 22 | -------------------------------------------------------------------------------- /searching/linear-search.py: -------------------------------------------------------------------------------- 1 | my_list = [4,8,3,7,1,0,9] 2 | 3 | ele = int(input()) 4 | 5 | flag = False 6 | for i in my_list: 7 | if(i == ele): 8 | flag = True 9 | break 10 | 11 | if(flag==True): 12 | print("Element found") 13 | else: 14 | print("Element not found") --------------------------------------------------------------------------------