├── .github ├── ISSUE_TEMPLATE │ └── implement-algorithm-in-different-languages.md └── pull_request_template.md ├── .gitignore ├── CODEOWNERS ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── Readme.md ├── _config.yml ├── classicalAlgos ├── 0-1KnappSack │ └── 0-1Knapp.cpp ├── checkPalindrome │ ├── palindrome.c │ ├── palindrome.cs │ ├── palindrome.go │ ├── palindrome.java │ ├── palindrome_WithIterators.cpp │ ├── palindromechecker.py │ └── stringPalindrome.cpp ├── dijkstrasAlgorithm │ ├── dijkstra.c │ ├── dijkstra.cpp │ ├── dijkstra.go │ ├── dijkstra.java │ ├── dijkstra.js │ ├── dijkstraEfficient.cpp │ └── disjkstrasAlgorithm.py ├── kadanesAlgorithm │ ├── kadanesAlgorithm.c │ ├── kadanesAlgorithm.cpp │ ├── kadanesAlgorithm.java │ ├── kadanesAlgorithm.js │ ├── kadanesAlgorithm.py │ └── readme.md ├── kosarajusAlgorithm │ ├── kosarajus.c │ └── kosarajus.cpp ├── kruskalsAlgorithm │ ├── kruskals.c │ ├── kruskals.cpp │ ├── kruskals.java │ └── kruskalsAlg.cs ├── lowestCommonAncestorBinaryTrees │ └── lowestCommonAncestor.c ├── primsAlgoMST │ ├── primsAlgorithmMST.cpp │ ├── primsAlgorithmMST.cs │ ├── primsAlgorithmMST.java │ └── primsAlgorithmMST.py ├── tarjansAlgo │ └── tarjansAlgo.java └── tries │ └── tries.cpp ├── graphColoringAlgo ├── greedyGraphColoring │ ├── greedyGraphColoring.c++ │ ├── greedyGraphColoring.java │ └── greedyGraphColoring.py └── welshPowellAlgo │ ├── welshPowellAlgo.c │ ├── welshPowellAlgo.cpp │ └── welshPowellAlgo.py ├── machineLearningAlgorithms ├── Perceptron │ └── python │ │ ├── README.md │ │ ├── images │ │ ├── Acc.png │ │ ├── algorithm.png │ │ └── perceptron.gif │ │ ├── main.py │ │ ├── perceptron.py │ │ ├── plotting.py │ │ ├── requirements.txt │ │ └── test.py └── kMeans │ └── kMeans.py ├── primalityTest ├── Sieve of Eratosthenes │ ├── SieveOfEratosthenes.c │ ├── SieveofEratosthenes.cpp │ └── sieveOfEratosthenes.java ├── fermatMethod │ ├── FermatMethod.java │ └── fermatMethod.cpp ├── millerRabinMethod │ ├── MillerRabinMethod.cs │ ├── MillerRabinMethod.java │ └── miller_rabin_method.py ├── optimisedSchoolMethod │ ├── README.md │ └── optimisedSchoolMethod.py └── solovayStrassenMethod │ └── solovayStrassenMethod.py ├── searchingAlgo ├── binarySearch │ ├── BinarySearch.c │ ├── BinarySearchWithDuplicateElements.cpp │ ├── binarySearch.cpp │ ├── binarySearch.dart │ ├── binarySearch.go │ ├── binarySearch.java │ ├── binarySearch.js │ ├── binarySearch.py │ ├── binarySearchRecursive.cpp │ ├── binarySearch_scratch.c │ ├── readme.md │ └── while_loop_binary_search.py ├── breadthFirstSearch │ ├── BFS.java │ ├── BFS.py │ ├── BreadthFirstSearch.c │ ├── BreadthFirstSearch.cpp │ └── BreadthFirstSearch.cs ├── depthFirstSearch │ ├── depthFirstSearch.c │ ├── depthFirstSearch.cs │ ├── depthFirstSearch.js │ ├── depthFirstSearch.kt │ └── depthfirstsearch.cpp ├── exponentialSearch │ ├── README.md │ ├── exponentialSearch.c │ ├── exponentialSearch.cpp │ ├── exponentialSearch.java │ └── exponentialSearch.py ├── fibonacciSearch │ ├── FibonacciSearch.cs │ ├── Fibonacci_Search.cpp │ ├── fibonacciSearch.c │ ├── fibonacciSearch.py │ └── fibonacciSearch.py.py ├── interpolationSearch │ ├── InterpolationSearch.java │ ├── interpolationSearch.c │ ├── interpolationSearch.cpp │ └── interpolationSearch.py ├── jumpSearch │ ├── jumpSearch.cpp │ └── jumpSearch.py ├── kmpSearch │ └── kmpSearch.py ├── linearSearch │ ├── README.md │ ├── linearSearch.c │ ├── linearSearch.cpp │ ├── linearSearch.js │ └── linearSearch.py ├── rabinKarpSearch │ ├── rabinKarp.c │ ├── rabinKarp.cpp │ └── rabinKarp.py ├── sublistSearch │ ├── SublistSearch.cpp │ ├── sublistSearch.java │ └── sublistSearch.py └── ternarySearch │ ├── Readme.md │ └── ternarySearch.py └── sortingAlgo ├── bubbleSort ├── Readme.md ├── bubbleSort.c ├── bubbleSort.cpp ├── bubbleSort.java ├── bubbleSort.js ├── bubbleSort.lua └── bubbleSort.py ├── bucketsort ├── BucketSort.c ├── BucketSort.cpp ├── BucketSort.java ├── BucketSort.py ├── Readme.md ├── bucketSort.js └── bucketSort.lua ├── cocktailSort ├── cocktailSort.c ├── cocktailSort.cpp ├── cocktailSort.go ├── cocktailSort.js ├── cocktailSort.lua ├── cocktailSort.py └── cocktailsort.java ├── combSort ├── combSort.c ├── combSort.cpp ├── combSort.cs ├── combSort.java ├── combSort.lua └── combSort.py ├── countingSort ├── README.md ├── countingSort.c ├── countingSort.cpp ├── countingSort.lua └── countingSort.py ├── cycleSort ├── README.md ├── cycleSort.c ├── cycleSort.cpp ├── cycleSort.java ├── cycleSort.js ├── cycleSort.lua ├── cycleSort.py └── cycleSort.rb ├── heapSort ├── README.md ├── heapSort.cpp ├── heapSort.lua ├── heapSort.py ├── heapSort.rs └── heapsort.c ├── insertionSort ├── InsertionSort.c ├── InsertionSort.cpp ├── Readme.md ├── insertionSort.cc ├── insertionSort.java ├── insertionSort.js ├── insertionSort.lua └── insertionSort.py ├── mergeSort ├── MergeSortC++.cpp ├── Readme.md ├── mergeSort.c ├── mergeSort.java ├── mergeSort.lua ├── mergeSort.py └── mergeSort.swift ├── pigeonholeSort ├── Readme.md ├── pigeonholeSort.c ├── pigeonholeSort.cpp ├── pigeonholeSort.cs ├── pigeonholeSort.java ├── pigeonholeSort.js ├── pigeonholeSort.lua └── pigeonholeSort.py ├── quickSort ├── QuickSort.java ├── README.md ├── quickSort.c ├── quickSort.cpp ├── quickSort.cs ├── quickSort.js ├── quickSort.lua ├── quickSort.py └── quickSortRandomized.cpp ├── radixSort ├── radixSort.cpp ├── radixSort.java ├── radixSort.lua ├── radixSort.py └── radixSort_withNegatives.cpp ├── selectionSort ├── selectionSort.cc ├── selectionSort.lua ├── selectionSort.md ├── selectionSort.py └── selectionsort.c ├── shellSort ├── Readme.md ├── ShellSort.c ├── ShellSort.cpp ├── ShellSort.java ├── ShellSort.py └── shellSort.lua └── timSort ├── TimSort.java ├── timSort.c ├── timSort.cpp └── timSort.lua /.github/ISSUE_TEMPLATE/implement-algorithm-in-different-languages.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Implement algorithm in different languages 3 | about: Generic template per algo 4 | title: '' 5 | labels: algorithm, good first issue, hacktoberfest 6 | assignees: '' 7 | 8 | --- 9 | 10 | Implement in a language of your choice. 11 | 12 | Please read the contributing guidelines in [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) 13 | 14 | Languages claimed/implemented: 15 | - [ ] C 16 | - [ ] C++ 17 | - [ ] Java 18 | - [ ] Python 19 | - [ ] Any other language 20 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | This PR implements the code for in referred in issue # 6 | 7 | I have read the contributing guidelines in [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) and have ensured the following: 8 | 9 | - [ ] My code is placed in the required directory as outlined in [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) 10 | - [ ] My code file is named according to [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) 11 | - [ ] Variables, classes, functions etc. follow camel case as outlined in [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) 12 | - [ ] My code hasn't been implemented or claimed by someone else and I have checked the present [issues](https://github.com/deutranium/Algorithms/issues) and [PRs](https://github.com/deutranium/Algorithms/pulls) for the same 13 | - [ ] **My code is well commented** 14 | - [ ] If my code is the first implementation of , I have added the link to this directory in [README.md](https://github.com/deutranium/Algorithms/blob/master/Readme.md) 15 | - [ ] I have **not** copied my code from anywhere 16 | 17 | 18 | 19 | This PR creates/modifies the README for 20 | 21 | I have read the contributing guidelines in [CONTRIBUTING.md](https://github.com/deutranium/Algorithms/blob/master/CONTRIBUTING.md) and have ensured the following: 22 | 23 | - [ ] Algo name (as heading) 24 | - [ ] A small description about algo 25 | - [ ] Time Complexity (Worst, Average, Best case) 26 | - [ ] Space Complexity (Worst, Average, Best case) 27 | - [ ] Logic and Pseudocode 28 | - [ ] Instructions for running code 29 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ################################################################################ 2 | # This .gitignore file was automatically created by Microsoft(R) Visual Studio. 3 | ################################################################################ 4 | 5 | /.vs 6 | 7 | ## MacOS X Desktop Services 8 | .DS_Store 9 | 10 | ## Visual Studio Code 11 | .vscode 12 | -------------------------------------------------------------------------------- /CODEOWNERS: -------------------------------------------------------------------------------- 1 | # automatically add reviewers to PRs 2 | * @deutranium @KyaBacchaHai @arushi-mittal @inesane @codelixir 3 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guidelines 2 | 3 | ## Steps to contribute 4 | 5 | - Check the code along with the issues and PR section if someone else has already worked on or is working on the algo and language you're interested in. If true, either implement it in a different language, or choose a different algo 6 | 7 | - Create (if not already created) an issue specifying the **algorithm name** and the **language** you want to implement it in. If the issue has been created by someone else, comment the language you will be working with for the concerned algo. 8 | 9 | - **Fork the repo, write the required code, commit using descriptive messages, push to your fork** 10 | 11 | - Make a PR with the title containing algorithm name and the language. 12 | 13 | ### Naming Conventions: 14 | It is preferred to use [camel case](https://en.wikipedia.org/wiki/Camel_case) in the naming of directories, files, variables, function names etc. 15 | 16 | In case you have a modified version of the algorithm, you can use `_` as a separator to create this distinction. \ 17 | (For example, [`radixSort_withNegatives.cpp`](sortingAlgo/radixSort/radixSort_withNegatives.cpp), [`palindrome_WithIterators.cpp`](classicalAlgos/checkPalindrome/palindrome_WithIterators.cpp), etc). Otherwise, stick to camel case. 18 | 19 | 20 | ## Directory and file structure 21 | 22 | For an algorithm say `algoName`, which is a type of a *searching algorithm*, the directory structure would be like: 23 | ``` 24 | \ 25 | |- sortingAlgo 26 | |- searchingAlgo 27 | |- algoName 28 | |- algoName.c 29 | |- algoName.js 30 | |- algoName.py 31 | |- someOtherAlgo 32 | |- someOtherOtherAlgo 33 | |-someOtherTypeOfAlgo 34 | ``` 35 | 36 | ## Code 37 | 38 | ### Format of code: 39 | Write the main code in a function with the name of the function being the algorithm name, and having parameters as required. The return value should be the answer required to be printed. 40 | 41 | For example, for a searching algorithm, we can have the function as `someSearch(arr, x)`, and the return value as the index of `x` in `arr`. 42 | 43 | ### Test Case: 44 | It is preferred to have at least one testcase within the code instead of getting the input, and its output being printed by calling the function like `print(funName(arr,x))` etc. 45 | 46 | ### Stylistic guidelines: 47 | - Ensure that the code is properly indented 48 | - Preferably have some (not too many) comments to describe the logic 49 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | theme: jekyll-theme-slate -------------------------------------------------------------------------------- /classicalAlgos/0-1KnappSack/0-1Knapp.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | #define ll long long int 4 | 5 | // https://practice.geeksforgeeks.org/problems/0-1-knapsack-problem/0 6 | 7 | void solve() 8 | { 9 | int n, w; 10 | cin >> n; 11 | cin >> w; 12 | int dp[n + 1][w]; 13 | vector wt(n + 1), v(n + 1); 14 | for (int i = 1; i <= n; i++) 15 | cin >> v[i]; 16 | for (int i = 1; i <= n; i++) 17 | cin >> wt[i]; 18 | int ma = 0; 19 | for (int i = 0; i <= n; i++) 20 | for (int j = 0; j <= w; j++) 21 | { 22 | if (i == 0 || j == 0) 23 | { 24 | dp[i][j] = 0; 25 | continue; 26 | } 27 | if (wt[i] <= j) 28 | dp[i][j] = max(dp[i - 1][j], dp[i - 1][max(0, j - wt[i])] + v[i]); 29 | else 30 | dp[i][j] = dp[i - 1][j]; 31 | ma = max(ma, dp[i][j]); 32 | } 33 | cout << ma << endl; 34 | } 35 | 36 | int main() 37 | { 38 | ios_base::sync_with_stdio(false); 39 | cin.tie(NULL); 40 | cout.tie(NULL); 41 | int t = 1; 42 | cin >> t; 43 | while (t--) 44 | solve(); 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /** 6 | * Function to check if a string is palindrome. 7 | * @param s string to check. 8 | * @return true if the string is palindrome; false otherwise. 9 | */ 10 | bool checkPalindrome(const char *s) { 11 | int front = 0; // Index pointing to the first character of the string 12 | int back = strlen(s) - 1; // Index pointing to the last valid character of the string 13 | 14 | // Every time front moves forward, back moves back, both towards the center 15 | while (front < back) { // Compare front and back 16 | if (s[front] != s[back]) { 17 | return false; 18 | } 19 | front++; 20 | back--; 21 | } 22 | 23 | return true; 24 | } 25 | 26 | /** 27 | * Driver code. 28 | */ 29 | int main() { 30 | char s[100]; // Assuming the input string has a maximum length of 99 characters 31 | scanf("%s", s); 32 | 33 | if (checkPalindrome(s)) { 34 | printf("Palindrome\n"); 35 | } else { 36 | printf("Not Palindrome\n"); 37 | } 38 | 39 | return 0; 40 | } -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/palindrome.cs: -------------------------------------------------------------------------------- 1 | static void Main(string[] args) 2 | { 3 | string inputString, reverseString = string.Empty; 4 | 5 | Console.Write("Enter a input: "); 6 | 7 | inputString = Console.ReadLine(); 8 | 9 | if (inputString != null) 10 | { 11 | for (int i = inputString.Length - 1; i >= 0; i--) 12 | reverseString += inputString[i].ToString(); 13 | 14 | if (reverseString == inputString) 15 | Console.WriteLine("Palindrome!"); 16 | 17 | else 18 | Console.WriteLine("Not Palindrome"); 19 | } 20 | 21 | Console.ReadLine(); 22 | } 23 | -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/palindrome.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func main() { 6 | 7 | fmt.Printf("Enter string to be checked: ") 8 | 9 | var str_in string 10 | fmt.Scanln(&str_in) 11 | // take user input 12 | 13 | n := len([]rune(str_in)) 14 | str_check := "" 15 | 16 | // reversing the input string and storing it in str_check 17 | for i := n - 1; i >= 0; i-- { 18 | str_check += string(str_in[i]) 19 | } 20 | 21 | // if string == its reverse, it's a palindrome 22 | if str_check == str_in { 23 | fmt.Println("Palindrome.") 24 | } else { 25 | fmt.Println("Not a palindrome.") 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/palindrome.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | class palindrome 3 | { 4 | public static void main() 5 | { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.println("Enter your word"); 8 | String str = sc.nextLine(); 9 | String s = str; 10 | String st = ""; 11 | char ch;int i; 12 | for(i=0;i 2 | #include 3 | 4 | /** 5 | * Function to check if a string is palindrome. 6 | * @param s string to check. 7 | * @return true if the string is palindrome; false otherwise. 8 | */ 9 | bool checkPalindrome(std::string s) { 10 | auto front = s.cbegin(); // const_iterator pointing to the first character of the string 11 | auto back = s.cend() - 1; // const_iterator pointing to the last valid character of the string 12 | 13 | // every time front moves forward, back moves back, both towards the center 14 | while(front != back) { // compare front and back 15 | if(*front != *back) { return false; } 16 | front++; 17 | back--; 18 | } 19 | 20 | return true; 21 | } 22 | 23 | /** 24 | * Driver code. 25 | */ 26 | int main() { 27 | std::string s; 28 | std::cin >> s; 29 | 30 | if(checkPalindrome(s)) { std::cout << "Palindrome" << std::endl; } 31 | else { std::cout << "Not Palindrome" << std::endl; } 32 | 33 | return 0; 34 | } 35 | -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/palindromechecker.py: -------------------------------------------------------------------------------- 1 | '''A palindrome is a word, number, phrase, or other sequence 2 | of characters which reads the same backward as forward, such 3 | as madam, racecar,2002. 4 | In this code we are going to check whether the string or a 5 | number inputted by the user is a palindrome or not.''' 6 | 7 | 8 | 9 | def pnum(a): #function to check whether a number is palindrome or not 10 | s1=str(a) 11 | c=s1[::-1] 12 | if c==a: 13 | print("number is palindrome") 14 | else: 15 | print("number is not palindrome") 16 | 17 | 18 | 19 | def strpal(a): #function to check whether a string is palindrome or not 20 | m=a[::-1] 21 | if m==a: 22 | print("string is palindrome") 23 | else: 24 | print("string is not palindrome") 25 | 26 | 27 | 28 | #testcase 29 | while True: 30 | z=int(input("1. number palindrome\n2. string palindrome\n3. to exit the program==")) 31 | if z==1: 32 | a=input("number=") 33 | pnum(a) 34 | elif z==2: 35 | a=input("enter a string=") 36 | strpal(a) 37 | else: 38 | break 39 | 40 | -------------------------------------------------------------------------------- /classicalAlgos/checkPalindrome/stringPalindrome.cpp: -------------------------------------------------------------------------------- 1 | //to check if a string is palindrome or not 2 | 3 | #include 4 | using namespace std; 5 | 6 | int main() 7 | { 8 | string s; 9 | getline(cin, s); 10 | char ch; 11 | string str; 12 | for (int i = 0; i < s.length(); i++) 13 | { 14 | ch = s.at(i); 15 | if(ch != ' ') 16 | str = ch+str; 17 | } 18 | if(str == s) 19 | cout<<"Palindrome"< 4 | #include 5 | #include 6 | #include 7 | #define N 100 8 | #define I __INT_MAX__ 9 | 10 | typedef long long int ll; 11 | void dijkstra(ll m[][N], ll vertex, ll source, ll e) 12 | { 13 | ll dist[N]; 14 | ll min = I; 15 | ll included[N] = {0}; 16 | ll n; 17 | ll counter = 0; 18 | 19 | for (ll i = 1; i <= vertex; i++) 20 | { 21 | dist[i] = m[source][i]; 22 | if (dist[i] < min) 23 | { 24 | min = dist[i]; 25 | n = i; 26 | } 27 | } 28 | dist[source] = 0; 29 | 30 | while (counter < vertex) 31 | { 32 | 33 | counter++; 34 | included[source] = 1; 35 | included[n] = 1; 36 | 37 | for (ll u = 1; u <= vertex; u++) 38 | { 39 | if ((dist[n] + m[n][u] < dist[u]) && (included[u] == 0)) 40 | { 41 | dist[u] = dist[n] + m[n][u]; 42 | } 43 | } 44 | 45 | min = I; 46 | for (ll i = 1; i <= vertex; i++) 47 | { 48 | if ((dist[i] < min) && (included[i] == 0)) 49 | { 50 | min = dist[i]; 51 | n = i; 52 | } 53 | } 54 | } 55 | 56 | for (ll i = 1; i <= vertex; i++) 57 | { 58 | if (dist[i] != I) 59 | printf("%lld ", dist[i]); 60 | else 61 | printf("inf "); 62 | } 63 | printf("\n"); 64 | } 65 | int main() 66 | { 67 | ll n, e; 68 | 69 | scanf("%lld %lld", &n, &e); 70 | ll weightedEdges[3][N]; 71 | ll adjMatrix[N][N] = {0}; 72 | for (ll i = 0; i < e; i++) 73 | { 74 | //vertex 1, vertex 2, weight 75 | scanf("%lld %lld %lld", &weightedEdges[0][i], &weightedEdges[1][i], &weightedEdges[2][i]); 76 | } 77 | 78 | for (ll i = 0; i < e; i++) 79 | { 80 | ll j = weightedEdges[0][i]; 81 | ll k = weightedEdges[1][i]; 82 | adjMatrix[j][k] = weightedEdges[2][i]; 83 | } 84 | 85 | for (ll i = 1; i <= n; i++) 86 | { 87 | for (ll j = 1; j <= n; j++) 88 | { 89 | if (adjMatrix[i][j] == 0) 90 | { 91 | adjMatrix[i][j] = I; 92 | } 93 | } 94 | } 95 | } -------------------------------------------------------------------------------- /classicalAlgos/dijkstrasAlgorithm/dijkstra.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program for Dijkstra's single source shortest path algorithm. 2 | // The program is for adjacency matrix representation of the graph 3 | 4 | #include 5 | #include 6 | #include 7 | #define V 9 8 | 9 | int min_dist(int dist[], bool sptSet[]) 10 | { 11 | int min = INT_MAX, min_index; 12 | 13 | for (int v = 0; v < V; v++) 14 | if (sptSet[v] == false && dist[v] <= min) 15 | min = dist[v], min_index = v; 16 | 17 | return min_index; 18 | } 19 | 20 | void solution(int dist[]) 21 | { 22 | printf("Vertex \t\t Distance from Source\n"); 23 | for (int i = 0; i < V; i++) 24 | printf("%d \t\t %d\n", i, dist[i]); 25 | } 26 | 27 | void dijkstra(int graph[V][V], int src) 28 | { 29 | int dist[V]; 30 | 31 | bool sptSet[V]; 32 | for (int i = 0; i < V; i++) 33 | dist[i] = INT_MAX, sptSet[i] = false; 34 | 35 | 36 | dist[src] = 0; 37 | 38 | 39 | for (int count = 0; count < V - 1; count++) { 40 | int u = min_dist(dist, sptSet); 41 | 42 | sptSet[u] = true; 43 | 44 | for (int v = 0; v < V; v++) 45 | 46 | if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX 47 | && dist[u] + graph[u][v] < dist[v]) 48 | dist[v] = dist[u] + graph[u][v]; 49 | } 50 | 51 | solution(dist); 52 | } 53 | 54 | int main() 55 | { 56 | int graph[V][V]; 57 | 58 | for (int i = 0; i < V; i++) 59 | { 60 | for (int j = 0; j < V; j++) 61 | { 62 | graph[i][j]=rand()%9; 63 | } 64 | 65 | } 66 | 67 | dijkstra(graph, 0); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /classicalAlgos/dijkstrasAlgorithm/dijkstra.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class ShortestPath { 6 | static final int V = 5; 7 | int minDistance(int dist[], Boolean sptSet[]) 8 | { 9 | int min = Integer.MAX_VALUE, min_index = -1; 10 | for (int v = 0; v < V; v++) 11 | if (sptSet[v] == false && dist[v] <= min) { 12 | min = dist[v]; 13 | min_index = v; 14 | } 15 | return min_index; 16 | } 17 | void printSolution(int dist[], int n) 18 | { 19 | System.out.println("Distance of vertex from Source"); 20 | for (int i = 0; i < V; i++) 21 | System.out.println(i + " " + dist[i]); 22 | } 23 | void dijkstra(int graph[][], int src) 24 | { 25 | int dist[] = new int[V]; 26 | Boolean sptSet[] = new Boolean[V]; 27 | for (int i = 0; i < V; i++) { 28 | dist[i] = Integer.MAX_VALUE; 29 | sptSet[i] = false; 30 | } 31 | dist[src] = 0; 32 | for (int count = 0; count < V - 1; count++) { 33 | int u = minDistance(dist, sptSet); 34 | sptSet[u] = true; 35 | for (int v = 0; v < V; v++) 36 | if (!sptSet[v] && graph[u][v] != 0 && 37 | dist[u] != Integer.MAX_VALUE && dist[u] + graph[u][v] < dist[v]) 38 | dist[v] = dist[u] + graph[u][v]; 39 | } 40 | printSolution(dist, V); 41 | } 42 | public static void main(String[] args) 43 | { 44 | int graph[][] = new int[][] { { 0, 4, 0, 3, 0}, 45 | { 4, 0, 8, 0, 0}, 46 | { 0, 8, 0, 7, 0 }, 47 | { 0, 0, 7, 0, 9 }, 48 | { 0, 0, 0, 9, 0 }}; 49 | ShortestPath t = new ShortestPath(); 50 | t.dijkstra(graph, 0); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /classicalAlgos/dijkstrasAlgorithm/dijkstra.js: -------------------------------------------------------------------------------- 1 | function createGraph(V,E){ 2 | // V - Number of vertices in graph 3 | // E - Number of edges in graph (u,v,w) 4 | let adj_list = []; // Adjacency list 5 | for(let i = 0 ; i < V ; i++){ 6 | adj_list.push([]); 7 | } 8 | for(let i = 0 ; i < E.length ; i++){ 9 | adj_list[E[i][0]].push([E[i][1],E[i][2]]); 10 | adj_list[E[i][1]].push([E[i][0],E[i][2]]); 11 | } 12 | return adj_list; 13 | } 14 | 15 | function djikstra(graph, V, src) { 16 | let vis = Array(V).fill(0); 17 | let dist = []; 18 | for(let i=0;idist[mn][0]+edge[1]){ 35 | dist[edge[0]][0] = dist[mn][0]+edge[1]; 36 | dist[edge[0]][1] = mn; 37 | } 38 | } 39 | } 40 | 41 | return dist; 42 | } 43 | 44 | let src = 0; 45 | let V = 9; 46 | let E = [[0,1,4], [0,7,8], [1,7,11], [1,2,8], [7,8,7], [6,7,1], [2,8,2], 47 | [6,8,6], [5,6,2], [2,5,4], [2,3,7], [3,5,14], [3,4,9], [4,5,10]]; 48 | 49 | let graph = createGraph(V,E); 50 | let distances = djikstra(graph,V,0); 51 | console.log(distances); -------------------------------------------------------------------------------- /classicalAlgos/dijkstrasAlgorithm/dijkstraEfficient.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | const int V = 9; 5 | vector> adj[V]; //adj[i] stores pairs {vert,cost} 6 | int dist[V]; 7 | 8 | void make_Graph() 9 | { 10 | vector> edges = { 11 | {0, 1, 4}, {0, 7, 8}, {1, 7, 11}, {1, 2, 8}, {7, 8, 7}, {6, 7, 1}, {2, 8, 2}, {6, 8, 6}, {5, 6, 2}, {2, 5, 4}, {2, 3, 7}, {3, 5, 14}, {3, 4, 9}, {4, 5, 10}}; 12 | for (auto &vec : edges) 13 | { 14 | int sour = vec[0], dest = vec[1], cost = vec[2]; 15 | adj[sour].push_back({dest, cost}); 16 | adj[dest].push_back({sour, cost}); 17 | } 18 | } 19 | 20 | void dijkstra(int sour) 21 | { 22 | for (int x = 0; x < V; x++) 23 | { 24 | dist[x] = INT_MAX; 25 | } 26 | dist[sour] = 0; 27 | set> st; //Stores pairs {distance,vertex} 28 | st.insert({dist[sour], sour}); 29 | while (!st.empty()) 30 | { 31 | auto pa = *st.begin(); 32 | st.erase(st.begin()); 33 | int u = pa.second; 34 | int cost_u = pa.first; 35 | if (cost_u > dist[u]) 36 | continue; 37 | for (auto &neb : adj[u]) 38 | { 39 | int v = neb.first; 40 | int weight = neb.second; 41 | if (dist[v] > dist[u] + weight) 42 | { 43 | st.erase({dist[v], v}); 44 | dist[v] = dist[u] + weight; 45 | st.insert({dist[v], v}); 46 | } 47 | } 48 | } 49 | } 50 | 51 | int main() 52 | { 53 | make_Graph(); 54 | dijkstra(0); 55 | for(int x=0;x 2 | 3 | //Function to calculate the maximum sum of a sub-array of a given array using kadane's algorithm 4 | int maxSumarray(int a[], int size){ 5 | int i; 6 | int max_sum_so_far=0; 7 | int max_ending_here = 0; 8 | for(i=0;i 2 | #define endl '\n' // pls remove while debugging 3 | #define ll long long int 4 | using namespace std; 5 | 6 | int kadane(vector a) { 7 | int res = INT32_MIN; 8 | int cur = 0; 9 | int n = a.size(); 10 | for (int i =0; i>n; 21 | 22 | vector a(n); 23 | for (int i =0; i>a[i]; 24 | 25 | cout< 2 | #include 3 | #include 4 | 5 | #define N 1000005 6 | #define I 10000000005 7 | 8 | typedef long long int ll; 9 | typedef struct Node 10 | { 11 | ll cost; 12 | ll vertex1; 13 | ll vertex2; 14 | } Node; 15 | int comparator(const void *a, const void *b) 16 | { 17 | return ((*(Node *)a).cost - (*(Node *)b).cost); 18 | } 19 | ll parent(ll set[], ll i) 20 | { 21 | if (set[i] == i) 22 | return i; 23 | else 24 | { 25 | set[i] = parent(set, set[i]); 26 | return set[i]; 27 | } 28 | } 29 | void setUnion(ll set[], ll a, ll b) 30 | { 31 | a = parent(set, a); 32 | b = parent(set, b); 33 | if (a != b) 34 | set[b] = a; 35 | } 36 | void initSet(ll set[], ll v) 37 | { 38 | for (ll i = 0; i < v; i++) 39 | set[i] = i; 40 | } 41 | long long int kruskals(Node m[], ll e, ll n) 42 | { 43 | long long int sum = 0; 44 | ll set[N]; 45 | initSet(set, n); 46 | ll j = 0; 47 | ll counter = 0; 48 | qsort(m, e, sizeof(Node), comparator); 49 | while ((j < n - 1) && (counter < e)) 50 | { 51 | ll x = m[counter].vertex1, y = m[counter].vertex2; 52 | 53 | if ((parent(set, x) != parent(set, y)) && (counter < e)) 54 | { 55 | sum += m[counter].cost; 56 | setUnion(set, x, y); 57 | j++; 58 | } 59 | counter++; 60 | } 61 | return sum; 62 | } 63 | int main() 64 | { 65 | ll n = 0, X = 0; 66 | scanf("%lld %lld", &n, &X); 67 | Node edges[N]; 68 | assert(edges); 69 | for (ll i = 0; i < X; i++) 70 | { 71 | scanf("%lld %lld %lld", &edges[i].vertex1, &edges[i].vertex2, &edges[i].cost); 72 | } 73 | printf("%lld\n", kruskals(edges, X, n)); 74 | return 0; 75 | } -------------------------------------------------------------------------------- /classicalAlgos/kruskalsAlgorithm/kruskalsAlg.cs: -------------------------------------------------------------------------------- 1 | static void 2 | Main (string[]args) 3 | { 4 | int k = 1; 5 | int vert = 4; 6 | int e = 0; 7 | KGraph objGraph = new KGraph (vert); //Step 1 8 | KVertex[]vertcoll = objGraph.vertcoll; 9 | KEdge[]result = new KEdge[vert]; 10 | 11 | List < KEdge > edgecoll = new List < KEdge > (); //Step 2 12 | KEdge objEdge = new KEdge (); 13 | 14 | for (int i = 0; i < vert; i++) //Step 3 15 | { 16 | for (int j = i; j < vert; j++) 17 | { 18 | if (i != j) 19 | { 20 | Console.WriteLine ("KEdge weight from src{0} to destn{1}", i, 21 | j); 22 | int wt = int.Parse (Console.ReadLine ()); 23 | if (wt == 0) 24 | continue; 25 | objEdge = new KEdge (vertcoll[i], vertcoll[j], wt); 26 | edgecoll.Add (objEdge); 27 | k++; 28 | } 29 | } 30 | } 31 | 32 | objGraph.Edgecoll = edgecoll.ToList ().OrderBy (p = >p.weight).ToList (); 33 | 34 | KSubsets[]sub = new KSubsets[vert]; //Step 4 35 | KSubsets subobj; 36 | for (int i = 0; i < vert; i++) 37 | { 38 | subobj = new KSubsets (); 39 | subobj.parent = vertcoll[i]; 40 | subobj.rank = 0; 41 | sub[i] = subobj; 42 | } 43 | k = 0; 44 | while (e < vert - 1) 45 | { 46 | objEdge = objGraph.Edgecoll.ElementAt (k); 47 | KVertex x = find (sub, objEdge.V1, Array.IndexOf (objGraph.vertcoll, objEdge.V1), objGraph.vertcoll); //Step 5 48 | KVertex y = find (sub, objEdge.V2, Array.IndexOf (objGraph.vertcoll, objEdge.V2), objGraph.vertcoll); //Step 6 49 | if (x != y) 50 | { 51 | result[e] = objEdge; 52 | Union (sub, x, y, objGraph.vertcoll); 53 | e++; 54 | } 55 | k++; 56 | } 57 | 58 | for (int i = 0; i < e; i++) //Step 7 59 | { 60 | Console.WriteLine ("edge from src:{0} to dest:{1} with weight:{2}", 61 | result[i].V1.Label, result[i].V2.Label, 62 | result[i].weight); 63 | } 64 | return; 65 | } 66 | -------------------------------------------------------------------------------- /classicalAlgos/primsAlgoMST/primsAlgorithmMST.cpp: -------------------------------------------------------------------------------- 1 | // Time Complexity : O(ElogV) 2 | #include 3 | using namespace std; 4 | #define ll long long int 5 | void init() { 6 | 7 | ios_base::sync_with_stdio(false); 8 | cin.tie(NULL); cout.tie(NULL); 9 | 10 | #ifndef ONLINE_JUDGE 11 | freopen("input.txt", "r", stdin); 12 | freopen("output.txt", "w", stdout); 13 | #endif 14 | 15 | } 16 | 17 | class Graph { 18 | ll V; 19 | // Adjancency List 20 | vector> *l; 21 | public: 22 | Graph(ll V) { 23 | this->V = V; 24 | l = new vector>[V]; 25 | } 26 | 27 | void addEdge(ll u, ll v, ll wt) { 28 | l[u].push_back(make_pair(v, wt)); // vertex, weight 29 | l[v].push_back(make_pair(u, wt)); 30 | } 31 | 32 | ll prim_mst() { 33 | // Min heap to get the min wt edge everytime 34 | // Init a priority queue 35 | priority_queue, vector>, greater>> Q; 36 | 37 | // visited array denotes whether the vertex has been included in MST or not 38 | bool *visited = new bool[V] {0}; 39 | 40 | ll min_wt = 0; 41 | // Push the src node in the queue 42 | Q.push({0, 0}); // weight,vertex 43 | 44 | while (!Q.empty()) { 45 | auto best = Q.top(); 46 | Q.pop(); 47 | 48 | ll vertex = best.second; 49 | ll wt = best.first; 50 | 51 | if (visited[vertex]) { 52 | // already included in MST, discard the edge; 53 | continue; 54 | } 55 | 56 | // take the current edge as it has minimum weight 57 | // mark it visited 58 | // Or include it in MST set 59 | visited[vertex] = 1; 60 | min_wt += wt; 61 | 62 | // put all the edges from that vertex int the priority queue 63 | for (auto edge : l[vertex]) { 64 | ll to = edge.first; 65 | ll w = edge.second; 66 | if (!visited[to]) { 67 | Q.push({w, to}); 68 | } 69 | } 70 | } 71 | return min_wt; 72 | } 73 | }; 74 | 75 | int main() { 76 | init(); 77 | ll V, E; 78 | cin >> V >> E; 79 | Graph g(V); 80 | for (int i = 0; i < E; i++) { 81 | ll x, y, wt; 82 | cin >> x >> y >> wt; 83 | g.addEdge(x - 1, y - 1, wt); 84 | } 85 | 86 | cout << g.prim_mst() << endl; 87 | 88 | return 0; 89 | } 90 | -------------------------------------------------------------------------------- /classicalAlgos/primsAlgoMST/primsAlgorithmMST.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | class MST { 3 | static int V = 5; 4 | static int minKey(int[] key, bool[] mstSet) 5 | { 6 | int min = int.MaxValue, min_index = -1; 7 | 8 | for (int v = 0; v < V; v++) 9 | if (mstSet[v] == false && key[v] < min) { 10 | min = key[v]; 11 | min_index = v; 12 | } 13 | 14 | return min_index; 15 | } 16 | //Print MST 17 | static void printMST(int[] parent, int[, ] graph) 18 | { 19 | Console.WriteLine("Edge \tWeight"); 20 | for (int i = 1; i < V; i++) 21 | Console.WriteLine(parent[i] + " - " + i + "\t" + graph[i, parent[i]]); 22 | } 23 | //MST Function 24 | static void primMST(int[, ] graph) 25 | { 26 | int[] parent = new int[V]; 27 | int[] key = new int[V]; 28 | bool[] mstSet = new bool[V]; 29 | for (int i = 0; i < V; i++) { 30 | key[i] = int.MaxValue; 31 | mstSet[i] = false; 32 | } 33 | key[0] = 0; 34 | parent[0] = -1; 35 | for (int count = 0; count < V - 1; count++) { 36 | int u = minKey(key, mstSet); 37 | 38 | // Add the picked vertex 39 | // to the MST Set 40 | mstSet[u] = true; 41 | for (int v = 0; v < V; v++) 42 | if (graph[u, v] != 0 && mstSet[v] == false 43 | && graph[u, v] < key[v]) { 44 | parent[v] = u; 45 | key[v] = graph[u, v]; 46 | } 47 | } 48 | printMST(parent, graph); 49 | } 50 | 51 | // Driver Code 52 | public static void Main() 53 | { 54 | int[, ] graph = new int[, ] { { 0, 3, 0, 8, 0 }, 55 | { 3, 0, 3, 8, 5 }, 56 | { 0, 3, 0, 0, 7 }, 57 | { 8, 8, 0, 0, 9 }, 58 | { 0, 5, 7, 9, 0 } }; 59 | primMST(graph); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /classicalAlgos/primsAlgoMST/primsAlgorithmMST.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | import java.lang.*; 3 | import java.io.*; 4 | 5 | class MinSpanTree { 6 | // Vertices in Graph 7 | private static final int V = 5; 8 | 9 | // Finds Vertex with Min Key 10 | int minKey(int key[], Boolean mstSet[]) 11 | { 12 | // Initialize min value 13 | int min = Integer.MAX_VALUE, min_index = -1; 14 | 15 | for (int v = 0; v < V; v++) 16 | if (mstSet[v] == false && key[v] < min) { 17 | min = key[v]; 18 | min_index = v; 19 | } 20 | 21 | return min_index; 22 | } 23 | 24 | // To print MST Stored 25 | void printMST(int parent[], int graph[][]) 26 | { 27 | System.out.println("Edge \tWeight"); 28 | for (int i = 1; i < V; i++) 29 | System.out.println(parent[i] + " - " + i + "\t" + graph[i][parent[i]]); 30 | } 31 | 32 | // To print MST through matrix representation 33 | void prim_MST(int graph[][]) 34 | { 35 | // Array to store constructed MST 36 | int parent[] = new int[V]; 37 | 38 | // Key values used to pick minimum weight edge in cut 39 | int key[] = new int[V]; 40 | 41 | // To represent set of vertices included in MST 42 | Boolean mstSet[] = new Boolean[V]; 43 | 44 | // Initialize all keys as INFINITE 45 | for (int i = 0; i < V; i++) { 46 | key[i] = Integer.MAX_VALUE; 47 | mstSet[i] = false; 48 | } 49 | 50 | key[0] = 0; 51 | parent[0] = -1; 52 | for (int count = 0; count < V - 1; count++) { 53 | int u = minKey(key, mstSet); 54 | mstSet[u] = true; 55 | for (int v = 0; v < V; v++) 56 | if (graph[u][v] != 0 && mstSet[v] == false && graph[u][v] < key[v]) { 57 | parent[v] = u; 58 | key[v] = graph[u][v]; 59 | } 60 | } 61 | printMST(parent, graph); 62 | } 63 | 64 | public static void main(String[] args) 65 | { 66 | MinSpanTree t = new MinSpanTree(); 67 | int graph[][] = new int[rows][columns]; 68 | for(int i=0; i 0 and mstSet[v] == False and key[v] > self.graph[u][v]: 41 | key[v] = self.graph[u][v] 42 | parent[v] = u 43 | self.printMST(parent) 44 | g = Graph(5) 45 | g.graph = [ [0, 2, 0, 6, 0], 46 | [2, 0, 3, 8, 5], 47 | [0, 3, 0, 0, 7], 48 | [6, 8, 0, 0, 9], 49 | [0, 5, 7, 9, 0]] 50 | 51 | g.primMST(); -------------------------------------------------------------------------------- /classicalAlgos/tries/tries.cpp: -------------------------------------------------------------------------------- 1 | // https://www.hackerearth.com/practice/data-structures/advanced-data-structures/trie-keyword-tree/tutorial/ 2 | 3 | #include 4 | using namespace std; 5 | #define ll long long int 6 | 7 | struct trieNode 8 | { 9 | trieNode *sons[26]; 10 | int wt = 0; 11 | trieNode() 12 | { 13 | for (int i = 0; i < 25; i++) 14 | sons[i] = NULL; 15 | wt = 0; 16 | } 17 | }; 18 | 19 | void insert(trieNode *root, string s, int w) 20 | { 21 | // cout<<"in insert"<sons[s[i] - 'a'] == NULL) 27 | { 28 | trieNode *newNode = new trieNode; 29 | newNode->wt = max(newNode->wt, w); 30 | node->sons[s[i] - 'a'] = newNode; 31 | } 32 | node = node->sons[s[i] - 'a']; 33 | node->wt = max(node->wt, w); 34 | } 35 | return; 36 | } 37 | 38 | int search(trieNode *node, string s) 39 | { 40 | int ans = -1; 41 | int n = s.size(); 42 | for (int i = 0; i < n; i++) 43 | { 44 | if (node->sons[s[i] - 'a'] == NULL) 45 | return -1; 46 | node = node->sons[s[i] - 'a']; 47 | ans = node->wt; 48 | } 49 | return ans; 50 | } 51 | 52 | void solve() 53 | { 54 | int n, q; 55 | cin >> n >> q; 56 | string s; 57 | int wt; 58 | trieNode *root = new trieNode; 59 | while (n--) 60 | { 61 | cin >> s >> wt; 62 | insert(root, s, wt); 63 | } 64 | // cout<<"done inserting"<> s; 68 | cout << search(root, s) << endl; 69 | } 70 | } 71 | 72 | int main() 73 | { 74 | ios_base::sync_with_stdio(false); 75 | cin.tie(NULL); 76 | cout.tie(NULL); 77 | int t = 1; 78 | // cin >> t; 79 | while (t--) 80 | solve(); 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /graphColoringAlgo/greedyGraphColoring/greedyGraphColoring.py: -------------------------------------------------------------------------------- 1 | import random 2 | import itertools 3 | import networkx as nx 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | def greedyColoringAlgo(network, colors): 8 | nodes = list(network.nodes()) 9 | random.shuffle(nodes) 10 | for node in nodes: 11 | dict_neighbors = dict(network[node]) 12 | nodes_neighbors = list(dict_neighbors.keys()) 13 | 14 | forbidden_colors = [] 15 | for neighbor in nodes_neighbors: 16 | if len(network.nodes.data()[neighbor].keys()) == 0: 17 | continue 18 | else: 19 | forbidden_color = network.nodes.data()[neighbor] 20 | forbidden_color = forbidden_color['color'] 21 | forbidden_colors.append(forbidden_color) 22 | for color in colors: 23 | if color in forbidden_colors: 24 | continue 25 | else: 26 | network.nodes[node]['color'] = color 27 | break 28 | 29 | ## Create a graph, and an array of colors that has atleast (d+1) colors 30 | ## Where d is the highest degree of all the vertices. 31 | 32 | G = nx.Graph() 33 | G.add_nodes_from([1, 6]) 34 | G.add_edges_from([(1, 2), (1, 3),(1,4),(1,5),(1,6)]) 35 | G.add_edges_from([(2,3),(2, 4), (2,5),(2,6)]) 36 | G.add_edges_from([(3, 4), (3,5),(3,6)]) 37 | G.add_edges_from([(4,6)]) 38 | colors = ["red", "chocolate", "darkorange", "moccasin", "gold"] 39 | greedyColoringAlgo(G,colors) 40 | 41 | ## Visualization of graph can be done by the code below 42 | colors_nodes = [data['color'] for v, data in G.nodes(data=True)] 43 | plt.figure(1,figsize=(9,9)) 44 | nx.draw(G, node_color=colors_nodes, with_labels=True) 45 | plt.show -------------------------------------------------------------------------------- /graphColoringAlgo/welshPowellAlgo/welshPowellAlgo.py: -------------------------------------------------------------------------------- 1 | import random 2 | import itertools 3 | import networkx as nx 4 | import numpy as np 5 | import matplotlib.pyplot as plt 6 | 7 | def greedyColoringAlgo(network, colors): 8 | nodes = list(network.nodes()) 9 | nodes.sort(reverse=True) 10 | for node in nodes: 11 | dict_neighbors = dict(network[node]) 12 | nodes_neighbors = list(dict_neighbors.keys()) 13 | 14 | forbidden_colors = [] 15 | for neighbor in nodes_neighbors: 16 | if len(network.nodes.data()[neighbor].keys()) == 0: 17 | continue 18 | else: 19 | forbidden_color = network.nodes.data()[neighbor] 20 | forbidden_color = forbidden_color['color'] 21 | forbidden_colors.append(forbidden_color) 22 | for color in colors: 23 | if color in forbidden_colors: 24 | continue 25 | else: 26 | network.nodes[node]['color'] = color 27 | break 28 | 29 | ## Create a graph, and an array of colors that has atleast (d+1) colors 30 | ## Where d is the highest degree of all the vertices. 31 | 32 | G = nx.Graph() 33 | G.add_nodes_from([1, 6]) 34 | G.add_edges_from([(1, 2), (1, 3),(1,4),(1,5),(1,6)]) 35 | G.add_edges_from([(2,3),(2, 4), (2,5),(2,6)]) 36 | G.add_edges_from([(3, 4), (3,5),(3,6)]) 37 | G.add_edges_from([(4,6)]) 38 | colors = ["red", "chocolate", "darkorange", "moccasin", "gold"] 39 | greedyColoringAlgo(G,colors) 40 | 41 | ## Visualization of graph can be done by the code below 42 | colors_nodes = [data['color'] for v, data in G.nodes(data=True)] 43 | plt.figure(1,figsize=(9,9)) 44 | nx.draw(G, node_color=colors_nodes, with_labels=True) 45 | plt.show 46 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/README.md: -------------------------------------------------------------------------------- 1 | # Perceptron Learning Algorithm: 2 | --- 3 | 4 | >Note: This code is implemented from algorithm proposed by Frank Rosenblatt in 1943, later refined and carefully analyzed by Minsky and Papert in 1969. 5 | 6 | A single perceptron can only be used to implement linearly separable functions. It takes both real and boolean inputs and associates a set of weights to them, along with a bias. 7 | 8 | Our goal is to find the w vector that can perfectly classify positive inputs and negative inputs in our data. I will get straight to the algorithm. Here goes: 9 | 10 | ![perceptron algorithm](./images/algorithm.png "Algorthm") 11 | 12 | - We initialize w with some random vector. 13 | - We then iterate over all the examples in the data, (P U N) both positive and negative examples. 14 | - Now if an input x belongs to P, ideally the dot product w.x be greater than or equal to 0. 15 | - And if x belongs to N, the dot product MUST be less than 0. 16 | --- 17 | 18 | ## Steps to run the code: 19 | 20 | 1. Make sure you have Python 3.7 and a text editor installed. 21 | 2. Install the required packages using pip install -r requirements.txt. 22 | 3. In the main directory Run `python3 main.py` or `python main.py`. 23 | 4. And wait for the results. 24 | 25 | --- 26 | ## Result on the Dummy Dataset: 27 | 28 | ![perceptron result](./images/perceptron.gif "Results After Each Epoch") 29 | 30 | Result of Perceptron after Every Epoch 31 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/images/Acc.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deutranium/Algorithms/7b910773a26a4aef738a50613d7d3924531f2e1a/machineLearningAlgorithms/Perceptron/python/images/Acc.png -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/images/algorithm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deutranium/Algorithms/7b910773a26a4aef738a50613d7d3924531f2e1a/machineLearningAlgorithms/Perceptron/python/images/algorithm.png -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/images/perceptron.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/deutranium/Algorithms/7b910773a26a4aef738a50613d7d3924531f2e1a/machineLearningAlgorithms/Perceptron/python/images/perceptron.gif -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/main.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from perceptron import Perceptron 3 | from plotting import plot, plot_error_history 4 | 5 | """0. Create dataset""" 6 | train_data = ( # x, y, target 7 | (0.2, 0.3, 0), 8 | (0.8, 7, 0), 9 | (2, 1, 0), 10 | (2, 4, 0), 11 | (1, 1, 0), 12 | (2, 1, 0), 13 | (2, 2.8, 0), 14 | (2, 2.2, 0), 15 | (3, 1, 0), 16 | (5, 3, 1), 17 | (5, 4, 1), 18 | (4, 5, 1), 19 | (4, 7, 1), 20 | (5, 5.1, 1), 21 | (5.5, 6, 1), 22 | (6, 5, 1), 23 | (6, 6.5, 1), 24 | (6, 7, 1) 25 | ) 26 | 27 | validate_data = ( 28 | (1, 1), 29 | (2, 2), 30 | (2, 1), 31 | (5, 4), 32 | (6, 5), 33 | (6, 6) 34 | ) 35 | 36 | X_train = np.array([x[:2] for x in train_data]) # list comprehension 37 | X_validate = np.array([x[:2] for x in validate_data]) # list comprehension 38 | y = np.array([x[-1] for x in train_data]) 39 | 40 | """1.Initialization perceptron""" 41 | perceptron = Perceptron(epochs=25, eta=0.01) 42 | 43 | """2.perceptron training""" 44 | perceptron.train(X_train, target=y) 45 | print(f'Weights: {perceptron.w}') 46 | 47 | """3.Prediction""" 48 | prediction = perceptron.predict(X_train) 49 | print(f'Output (Y): {prediction}') 50 | 51 | print('last') 52 | plot(X_train, prediction, perceptron, 25, None, perceptron.w) 53 | plot_error_history(perceptron.err) 54 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/perceptron.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | from plotting import plot 3 | from sklearn.metrics import accuracy_score 4 | 5 | """ 6 | File: perceptron.py 7 | Author: Lashuk1729 8 | Description: Perceptron Rule 9 | """ 10 | 11 | 12 | class Perceptron(object): 13 | 14 | def __init__(self, eta: float = 0.01, epochs: int = 50): 15 | self.eta = eta # learning reate 16 | self.epochs = epochs 17 | 18 | def train(self, X: np.ndarray, target: np.ndarray): # Perceptron Rule 19 | self.w = np.zeros(1 + X.shape[1]) 20 | self.err = [] 21 | 22 | print('Training progress..') 23 | for epoch in range(self.epochs): 24 | errors = 0 25 | for x, y in zip(X, target): 26 | update = self.eta * (y - self.predict(x)) 27 | self.w[1:] += update * x 28 | self.w[0] += update 29 | errors += int(update != 0.0) 30 | 31 | accuracy = int(accuracy_score(self.predict(X), target) * 100) 32 | self.err.append(accuracy) 33 | plot(X, target, self, epoch, accuracy, self.w) 34 | return self 35 | 36 | def dot_product(self, X: np.ndarray) -> np.float64: 37 | return np.dot(X, self.w[1:]) + self.w[0] 38 | 39 | def predict(self, X: np.ndarray) -> int: 40 | return np.where(self.dot_product(X) >= 0.0, 1, 0) 41 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/plotting.py: -------------------------------------------------------------------------------- 1 | from mlxtend.plotting import plot_decision_regions 2 | import matplotlib.pyplot as plt 3 | 4 | 5 | def plot(x, prediction, clf, epoch=None, accuracy=None, weights=None): 6 | plot_decision_regions(x, prediction, clf=clf) 7 | 8 | plt.title(f'Perceptron {weights}') 9 | 10 | if epoch is not None: 11 | plt.annotate(f'Epoch: {epoch}', xy=(2, 0), xytext=(5, 0.5)) 12 | 13 | if accuracy is not None: 14 | plt.annotate(f'Accuracy: {accuracy}%', xy=(2, 0), xytext=(5, 0)) 15 | 16 | plt.xlabel('x') 17 | plt.ylabel('y') 18 | plt.show() 19 | 20 | 21 | def plot_error_history(err): 22 | print(len(err)) 23 | plt.plot(err) 24 | plt.show() 25 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/requirements.txt: -------------------------------------------------------------------------------- 1 | mlxtend==0.19.0 2 | numpy==1.22.0 3 | matplotlib==3.3.2 4 | scikit_learn==1.0 5 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/Perceptron/python/test.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | x = [1, 2] 5 | w = [1, 1, 1] 6 | 7 | 8 | def net_input(X: np.ndarray) -> np.float64: 9 | return np.dot(X, w[1:]) + w[0] 10 | 11 | 12 | def predict(X: np.ndarray) -> int: 13 | return 1.0 if net_input(X) >= 0.0 else 0.0 14 | 15 | 16 | print(predict(x)) 17 | -------------------------------------------------------------------------------- /machineLearningAlgorithms/kMeans/kMeans.py: -------------------------------------------------------------------------------- 1 | import random 2 | import itertools 3 | import numpy as np 4 | from sklearn.datasets import make_blobs 5 | 6 | class KMeans: 7 | def __init__(self,k): 8 | self.k = k 9 | self.means = None 10 | 11 | def form_clusters(self,data,indexes): 12 | #assigning clusters to points 13 | 14 | clusters = [[] for i in range(self.k)] 15 | means = [] 16 | for point,index in zip(data,indexes): 17 | clusters[index].append(point) 18 | for cluster in clusters: 19 | if cluster: 20 | means.append(np.mean(cluster,axis=0).tolist()) 21 | else: 22 | means.append(random.choice(data)) 23 | return means 24 | 25 | def classify(self,vector): 26 | 27 | diff = [] 28 | #calculating euclidean distance for each point from each center 29 | for mean in self.means: 30 | diff.append(np.linalg.norm(mean - vector)) 31 | return np.argmin(diff) 32 | 33 | @property 34 | def centers(self): 35 | return self.means 36 | 37 | def fit(self,data): 38 | 39 | #random initialization of means 40 | cluster_index = [random.randrange(self.k) for _ in data] 41 | for i in itertools.count(): 42 | #computing means and reassigning centers 43 | self.means = self.form_clusters(data,cluster_index) 44 | new_cluster_index = [self.classify(val) for val in data] 45 | 46 | #if difference between old centers and new centers is 0 then break the loop 47 | differences = 0 48 | for ind,new_ind in zip(cluster_index,new_cluster_index): 49 | if ind != new_ind: 50 | differences = differences + 1 51 | 52 | if differences == 0: 53 | return 54 | 55 | #calculating means for new cluster centers 56 | cluster_index = new_cluster_index 57 | self.means = self.form_clusters(data,cluster_index) 58 | 59 | #generating random dataset 60 | X,y= make_blobs(n_samples=150,n_features=2,centers=3) 61 | clustering = KMeans(k=3) 62 | clustering.fit(X) 63 | print(clustering.centers) 64 | 65 | -------------------------------------------------------------------------------- /primalityTest/Sieve of Eratosthenes/SieveOfEratosthenes.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void sieveOfEratosthenes(int number) 4 | { 5 | 6 | int i, j; 7 | int primes[number + 1]; 8 | 9 | for (i = 2; i <= number; i++) //populating array with naturals numbers 10 | primes[i] = i; 11 | 12 | i = 2; 13 | while ((i * i) <= number) 14 | { 15 | if (primes[i] != 0) 16 | { 17 | for (j = 2; j < number; j++) 18 | { 19 | if (primes[i] * j > number) 20 | break; 21 | else 22 | primes[primes[i] * j] = 0; // Instead of deleteing , making elemnets 0 23 | } 24 | } 25 | i++; 26 | } 27 | 28 | int result[number + 1]; 29 | int k = 0; 30 | for (i = 2; i <= number; i++) 31 | { 32 | //If number is not 0 then it is prime 33 | if (primes[i] != 0) 34 | { 35 | result[k++] = primes[i]; 36 | } 37 | } 38 | 39 | for (i = 0; i < k; i++) 40 | printf("%d ", result[i]); 41 | 42 | printf("\n"); 43 | } 44 | 45 | int main() 46 | { 47 | int number = 100; 48 | 49 | sieveOfEratosthenes(number); 50 | 51 | return 0; 52 | } 53 | 54 | /* 55 | TIme Complexity : O(nlog(logn)) 56 | Space Complexity : O(n) 57 | */ -------------------------------------------------------------------------------- /primalityTest/fermatMethod/fermatMethod.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | //Using logarithmic exponentiation 5 | int modpow(int a,int b , int mod){ 6 | int x=1; 7 | while(b){ 8 | if(b&1){ 9 | x*=a; 10 | x%=mod; 11 | } 12 | a*=a; 13 | a%=mod; 14 | b>>=1; 15 | } 16 | return x; 17 | } 18 | //Time complexity of modpow = O(log n) 19 | //using fermat's theorem that is If n is a prime number, then for every a, 1 < a < n-1, a^(n-1) ≡ 1 (mod n); 20 | bool isPrime(int n ,int k) 21 | { 22 | while(k--) 23 | { 24 | int a = 2 + rand()%(n-4); 25 | 26 | if(__gcd(a,n) != 1) 27 | return false; 28 | if (modpow(a, n-1, n) != 1) 29 | return false; 30 | 31 | } 32 | return true; 33 | } 34 | 35 | int main() 36 | { 37 | 38 | cout << isPrime(7 , 4) ; 39 | 40 | 41 | } 42 | 43 | /* 44 | Time complexity: O(k Log n) 45 | Space complexity: O(1) 46 | */ 47 | 48 | 49 | -------------------------------------------------------------------------------- /primalityTest/millerRabinMethod/miller_rabin_method.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | 4 | def miller_rabin_method(number: int, rounds: int = 40) -> bool: 5 | """Miller-Rabin primality test 6 | 7 | Test if number could be prime using the Miller-Rabin Primality Test with rounds rounds. 8 | A return value of false means number is definitely composite, while true means it is probably prime. 9 | The higher rounds is, the more accurate the test is. 10 | :param int number: The number to be tested for primality. 11 | :param int rounds: How many rounds to use in the test. 12 | :return: A bool indicating if the number could be prime or not. 13 | :rtype: bool 14 | 15 | """ 16 | # Handle corner cases 17 | if number == 1: 18 | return False 19 | if number == 2: 20 | return True 21 | if number == 3: 22 | return True 23 | 24 | # Factor out the powers of 2 from {number - 1} and save the result 25 | d = number - 1 26 | r = 0 27 | while not d & 1: 28 | d = d >> 1 29 | r += 1 30 | 31 | # Cycle at most {round} times 32 | for i in range(rounds + 1): 33 | a = random.randint(2, number - 2) 34 | x = pow(a, d, number) 35 | if x == 1 or x == number - 1: 36 | continue 37 | # Cycle at most {r - 1} times 38 | for e in range(r): 39 | x = x * x % number 40 | if x == number - 1: 41 | break 42 | if x == number - 1: 43 | continue 44 | return False 45 | return True 46 | 47 | 48 | if __name__ == "__main__": 49 | count = 0 50 | upper_bound = 1000 51 | print(f"Prime numbers lower than {upper_bound}:") 52 | for i in range(1, 1000): 53 | if miller_rabin_method(i): 54 | print(f"\t{i}") 55 | count += 1 56 | print(f"Total: {count}") -------------------------------------------------------------------------------- /primalityTest/optimisedSchoolMethod/README.md: -------------------------------------------------------------------------------- 1 | # Optimised School Method 2 | 3 | - Checks whether a Given Positive Integer is Prime or not. 4 | - Time Complexity: 5 | - Worst Case Complexity:O(√n) 6 | - Best Case Complexity:O(1) 7 | - Average Case Complexity:O(√n) 8 | - Worst Case Space Complexity:O(1) 9 | 10 | ### Logic 11 | 12 | 1. Firstly We Only check till √n numbers from 3. 13 | 2. We further Optimised the Algorithm by observing the pattern that all Prime Numbers are of the Form 6k ± 1 with exception of 1 and 2. 14 | 3. We check whether all (i+6)th number are divisible by given number and iterate till the √nth number. 15 | 4. Pseudo Code: 16 | 17 | 18 | function is_prime(n) 19 | if n ≤ 3 then 20 | return n > 1 21 | else if n mod 2 = 0 or n mod 3 = 0 22 | return false 23 | 24 | let i ← 5 25 | while i × i ≤ n do 26 | if n mod i = 0 or n mod (i + 2) = 0 27 | return false 28 | i ← i + 6 29 | 30 | return true 31 | ### Instruction for Running code: 32 | 33 | - Python 34 | ``` 35 | python3 optimisedSchoolMethod.py 36 | ``` 37 | -------------------------------------------------------------------------------- /primalityTest/optimisedSchoolMethod/optimisedSchoolMethod.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def optimisedSchoolMethod(): 4 | n = int(input()) 5 | 6 | if(n <= 1): 7 | return False 8 | 9 | if (n % 2 == 0) or (n % 3 == 0): 10 | return False 11 | 12 | for i in range(5, math.round(math.sqrt(n)), 6): 13 | if n % i == 0: 14 | return False 15 | 16 | return True 17 | optimisedSchoolMethod() 18 | #https://www.geeksforgeeks.org/primality-test-set-1-introduction-and-school-method/ 19 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/BinarySearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | //The below code is an algorithm implementing Binary search 4 | // It uses a while loop and has a time complexity of 5 | // O(N) = log(N) 6 | // Θ(N) = log(N) 7 | // Ω(N) = 1 ( constant ) 8 | 9 | 10 | int main(){ 11 | 12 | int start, end, mid, ans; 13 | 14 | int Arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; 15 | int X = 0 ; 16 | 17 | 18 | start = 0; //INITIALISE 19 | end = 10 ; // SIZE OF ARRAY 20 | ans = -1; // IF ELEMENT IS NOT FOUND -1 WOULD BE PRINTED 21 | 22 | while( start <= end ){ 23 | 24 | mid = (start + end)/2; // INITIALISE 25 | 26 | 27 | if( Arr[mid] == X){ 28 | ans = mid+1; 29 | break; 30 | } 31 | 32 | else if(Arr[mid] > X) 33 | end = mid-1; 34 | 35 | else 36 | start = mid +1; 37 | 38 | 39 | } 40 | 41 | printf("%d\n", ans); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A iterative binary search function. It returns location of x in given array arr[l..r] if present, otherwise -1 5 | 6 | int binarySearch(int arr[], int l, int r, int x) 7 | { 8 | while (l <= r) { 9 | int mid = l + (r - l) / 2; 10 | if (arr[mid] == x) 11 | return mid; 12 | 13 | if (arr[mid] < x) 14 | l = mid + 1; 15 | 16 | else 17 | r = mid - 1; 18 | } 19 | 20 | return -1; 21 | } 22 | 23 | int main() 24 | { 25 | int n ; 26 | cin>>n ; 27 | int arr[n] ; 28 | for(int i=0; i>arr[i] ; 30 | } 31 | int num ; 32 | cin>>num ; 33 | int result = binarySearch(arr, 0, n - 1, num); 34 | cout< arr, int x, int left, int right) { 7 | /// mid index of selected array 8 | int mid = left + (right - left) ~/ 2; 9 | 10 | // return -1 if x not in array 11 | if (mid >= arr.length || right < 1) { 12 | return -1; 13 | } 14 | 15 | // if value is equal to element in array mid index, return the index 16 | if (x == arr[mid]) { 17 | return mid; 18 | 19 | // if value is bigger than elemnt in array mid, search in the right half 20 | } else if (x > arr[mid]) { 21 | return binarySearch(arr, x, mid + 1, right); 22 | 23 | // otherwise search for the left half 24 | } else { 25 | return binarySearch(arr, x, left, mid - 1); 26 | } 27 | } 28 | 29 | /// Testcase 1 30 | var arr = [1, 5, 2, 3, 4, 5, 6, 7, 8, 9]; 31 | var x = 0; 32 | 33 | /// Testcase 2 34 | var arr2 = [1, 5, 2, 3, 4, 100, 6, 7, 11, 9]; 35 | var x1 = 1; 36 | 37 | void main(List args) { 38 | /// expect return equal to -1 39 | print(binarySearch(arr, x, 0, arr.length)); 40 | 41 | /// expect return equal to 0 42 | print(binarySearch(arr2, x1, 0, arr.length)); 43 | } 44 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearch.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | // recursive implementation of binary search 6 | func binarySearch(arr []int, x, l, r int) (int, bool) { 7 | 8 | // boundary condition 9 | if l > r { 10 | return -1, false 11 | } 12 | 13 | if mid := (r-l)/2 + l; arr[mid] == x { // when found, return the index 14 | return mid, true 15 | } else if arr[mid] < x { // if query element is greater than the middle, search the right half 16 | return binarySearch(arr, x, mid+1, r) 17 | } else { // if query element is less than the middle, search the left half 18 | return binarySearch(arr, x, l, mid-1) 19 | } 20 | } 21 | 22 | func main() { 23 | fmt.Printf("Enter number of elements in array: ") 24 | var n, x int 25 | fmt.Scanf("%d", &n) 26 | 27 | fmt.Printf("Enter the sorted array: ") 28 | var arr []int 29 | for i := 0; i < n; i++ { 30 | var k int 31 | fmt.Scanf("%d", &k) 32 | arr = append(arr, k) 33 | } 34 | 35 | fmt.Printf("Enter the element to be searched: ") 36 | fmt.Scanf("%d", &x) 37 | 38 | idx, found := binarySearch(arr, x, 0, n-1) 39 | 40 | if !found { 41 | fmt.Printf("Element %d not found.\n", x) 42 | } else { 43 | fmt.Printf("Element %d found at position %d.\n", x, idx) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearch.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | 3 | class BinarySearch { 4 | static int search(int arr[], int value, int leftIndex, int rightIndex) { 5 | // base case 6 | if (rightIndex < leftIndex) { 7 | return -1; 8 | } 9 | 10 | // calculate the mid index 11 | int midIndex = (rightIndex - leftIndex) / 2; 12 | midIndex += leftIndex; 13 | 14 | // if value is same as value on midIndex, simply return midIndex 15 | if (value == arr[midIndex]) { 16 | return midIndex; 17 | } else if (value < arr[midIndex]) { 18 | // when value is less than middle value, we search in the left half 19 | return search(arr, value, leftIndex, midIndex - 1); 20 | } else { 21 | // when value is greater than middle value, we search in the right half 22 | return search(arr, value, midIndex + 1, rightIndex); 23 | } 24 | } 25 | 26 | public static void main(String args[]) { 27 | // sorted array to search the value in 28 | int arr[] = { 10, 13, 15, 22, 89, 90 }; 29 | // value to search for 30 | int value = 15; 31 | 32 | // find the value 33 | int result = search(arr, value, 0, arr.length - 1); 34 | 35 | // show the result 36 | if (result == -1) { 37 | System.out.println("Item not found"); 38 | } else { 39 | System.out.println("Item found at index: " + result); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearch.js: -------------------------------------------------------------------------------- 1 | function binarySearch(arr, x) { 2 | let left = 0; 3 | let right = arr.length - 1; 4 | 5 | while (left <= right) { 6 | let mid = Math.round((left + right) / 2); // calculate the mid index 7 | 8 | // if value is same as value on midIndex, simply return midIndex 9 | if (arr[mid] == x) { 10 | return mid; 11 | } 12 | 13 | // when value is less than middle value, we search in the left half 14 | if (arr[mid] < x) { 15 | left = mid + 1; 16 | 17 | // when value is greater than middle value, we search in the right half 18 | } else { 19 | right = mid - 1; 20 | } 21 | } 22 | return -1; 23 | } 24 | 25 | // testCase 26 | // sorted array to search the value in 27 | const arr = [2, 12, 23, 34, 45, 52, 61, 75, 85, 99]; 28 | const x = 85; 29 | 30 | console.log(binarySearch(arr, x)); 31 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearch.py: -------------------------------------------------------------------------------- 1 | def recur(arr, x, lo, hi): 2 | mid = (lo + hi)//2 3 | 4 | if x == arr[mid]: 5 | return mid 6 | elif x > arr[mid]: 7 | return(recur(arr, x, mid, hi)) 8 | else: 9 | return(recur(arr, x, lo, mid)) 10 | 11 | # Testcase 12 | arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 13 | x = 2 14 | 15 | try: 16 | print(recur(arr, x, 0, len(arr))) 17 | except: 18 | print(-1) 19 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/binarySearchRecursive.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | // recursive binary search for a sorted array 4 | bool binse(int arr[],int l,int h,int x) 5 | { 6 | if(l>h) 7 | return -1; 8 | int mid=l+(h-l)/2; //causes (l+h)/2 overloading so l+(h-l)/2 is preferred 9 | if(arr[mid]==x) 10 | return mid; 11 | if(arr[mid]>x) 12 | return binse(arr,l,mid-1,x); 13 | else 14 | return binse(arr,mid+1,h,x); 15 | } 16 | int main() { 17 | int n; 18 | cin>>n; 19 | int arr[n]; 20 | for(int i=0;i>arr[i]; 22 | int x; 23 | cin>>x;//number to be searched 24 | int l=0,h=n-1;//lower limit and higher limit 25 | int pos=binse(arr,l,h,x); 26 | if(pos>=0) 27 | cout<<"The element is found at "<**Read this or your laptop *(or phone or whatever)* will burst:**
19 | I haven't considered duplicate elements to be present in the array(yet). If need to consider that too, then well... use some brains :grin: 20 | -------------------------------------------------------------------------------- /searchingAlgo/binarySearch/while_loop_binary_search.py: -------------------------------------------------------------------------------- 1 | """The below code is an algorithm implementing Binary search 2 | It uses a while loop and has a time complexity of 3 | O(N) = log(N) 4 | Θ(N) = log(N) 5 | Ω(N) = 1 ( constant ) 6 | """ 7 | def search( arr , X ) : 8 | ans = -1 9 | start = 0 10 | end = len(arr) 11 | 12 | while end >= start : 13 | mid = (start+end)//2 14 | 15 | if( arr[mid] == X ): 16 | ans = mid 17 | break 18 | 19 | elif ( arr[mid] > X ): 20 | end = mid -1 21 | 22 | else : 23 | start = mid +1 24 | 25 | #The solution will be in zero based indexing 26 | print( ans ) 27 | 28 | 29 | 30 | # Testcase 31 | arr = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ] 32 | x = 2 33 | 34 | search( arr , x) 35 | """ The function search() automatically prints the result 36 | hence a seperate print statement doesn't need to be added 37 | This can however be easily modified by removing the last 38 | statement and adding " return mid " -------------------------------------------------------------------------------- /searchingAlgo/breadthFirstSearch/BFS.java: -------------------------------------------------------------------------------- 1 | // BFS java implementation to find path from the source vertex in a given graph 2 | import java.io.*; 3 | import java.util.*; 4 | class Graph 5 | { 6 | private int V; 7 | private LinkedList adj[]; 8 | Graph(int v) // initialize graph 9 | { 10 | V = v; 11 | adj = new LinkedList[v]; 12 | for (int i=0; i queue = new LinkedList(); 23 | visited[s]=true; 24 | queue.add(s); 25 | 26 | while (queue.size() > 0) 27 | { 28 | s = queue.poll(); 29 | System.out.print(s+" "); 30 | Iterator i = adj[s].listIterator(); 31 | while (i.hasNext()) 32 | { 33 | int n = i.next(); 34 | if (!visited[n]) 35 | { 36 | visited[n] = true; 37 | queue.add(n); 38 | } 39 | } 40 | } 41 | } 42 | public static void main(String args[]) // sample graph 43 | { 44 | Graph g = new Graph(4); 45 | 46 | g.addEdge(0, 1); 47 | g.addEdge(0, 2); 48 | g.addEdge(1, 2); 49 | g.addEdge(2, 3); 50 | g.BFS(2); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /searchingAlgo/breadthFirstSearch/BFS.py: -------------------------------------------------------------------------------- 1 | # BFS python implementation to find path from the source vertex in a given graph 2 | from collections import defaultdict 3 | class Graph: 4 | # Graph initialization 5 | def __init__(self): 6 | self.graph = defaultdict(list) 7 | def addEdge(self,u,v): 8 | self.graph[u].append(v) 9 | def BFS(self, s): 10 | visited = [0]*(len(self.graph)) # initializing all nodes as not visited 11 | queue = [] 12 | queue.append(s) 13 | visited[s] = 1 # initializing source as visited 14 | while queue: # traversing through all nodes reachable 15 | s = queue.pop(0) 16 | print (s, end = " ") 17 | for i in self.graph[s]: 18 | if visited[i] == 0: 19 | queue.append(i) 20 | visited[i] = 1 21 | # sample graph to run 22 | g = Graph() 23 | g.addEdge(0, 1); 24 | g.addEdge(0, 2); 25 | g.addEdge(1, 2); 26 | g.addEdge(2, 3); 27 | g.BFS(2) 28 | 29 | -------------------------------------------------------------------------------- /searchingAlgo/breadthFirstSearch/BreadthFirstSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | int a[20][20], q[20], visited[20], n, i, j, f = 0, r = -1; 3 | 4 | void bfs(int v) { 5 | for(i = 1; i <= n; i++) 6 | if(a[v][i] && !visited[i]) 7 | q[++r] = i; 8 | if(f <= r) { 9 | visited[q[f]] = 1; 10 | bfs(q[f++]); 11 | } 12 | } 13 | 14 | void main() { 15 | int v; 16 | printf("\n Enter the number of vertices:"); 17 | scanf("%d", &n); 18 | 19 | for(i=1; i <= n; i++) { 20 | q[i] = 0; 21 | visited[i] = 0; 22 | } 23 | 24 | printf("\n Enter graph data in matrix form:\n"); 25 | for(i=1; i<=n; i++) { 26 | for(j=1;j<=n;j++) { 27 | scanf("%d", &a[i][j]); 28 | } 29 | } 30 | 31 | printf("\n Enter the starting vertex:"); 32 | scanf("%d", &v); 33 | bfs(v); 34 | printf("\n The node which are reachable are:\n"); 35 | 36 | for(i=1; i <= n; i++) { 37 | if(visited[i]) 38 | printf("%d\t", i); 39 | else { 40 | printf("\n Bfs is not possible. Not all nodes are reachable"); 41 | break; 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /searchingAlgo/breadthFirstSearch/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | // This class represents a directed graph using 7 | // adjacency list representation 8 | class Graph 9 | { 10 | int V; // No. of vertices 11 | 12 | // Pointer to an array containing adjacency 13 | // lists 14 | list *adj; 15 | public: 16 | Graph(int V); // Constructor 17 | 18 | // function to add an edge to graph 19 | void addEdge(int v, int w); 20 | 21 | // prints BFS traversal from a given source s 22 | void BFS(int s); 23 | }; 24 | 25 | Graph::Graph(int V) 26 | { 27 | this->V = V; 28 | adj = new list[V]; 29 | } 30 | 31 | void Graph::addEdge(int v, int w) 32 | { 33 | adj[v].push_back(w); // Add w to v’s list. 34 | } 35 | 36 | void Graph::BFS(int s) 37 | { 38 | // Mark all the vertices as not visited 39 | bool *visited = new bool[V]; 40 | for(int i = 0; i < V; i++) 41 | visited[i] = false; 42 | 43 | // Create a queue for BFS 44 | list queue; 45 | 46 | // Mark the current node as visited and enqueue it 47 | visited[s] = true; 48 | queue.push_back(s); 49 | 50 | // 'i' will be used to get all adjacent 51 | // vertices of a vertex 52 | list::iterator i; 53 | 54 | while(!queue.empty()) 55 | { 56 | // Dequeue a vertex from queue and print it 57 | s = queue.front(); 58 | cout << s << " "; 59 | queue.pop_front(); 60 | 61 | // Get all adjacent vertices of the dequeued 62 | // vertex s. If a adjacent has not been visited, 63 | // then mark it visited and enqueue it 64 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 65 | { 66 | if (!visited[*i]) 67 | { 68 | visited[*i] = true; 69 | queue.push_back(*i); 70 | } 71 | } 72 | } 73 | } 74 | 75 | // Driver program to test methods of graph class 76 | int main() 77 | { 78 | // Create a graph given in the above diagram 79 | Graph g(4); 80 | g.addEdge(0, 1); 81 | g.addEdge(0, 2); 82 | g.addEdge(1, 2); 83 | g.addEdge(2, 0); 84 | g.addEdge(2, 3); 85 | g.addEdge(3, 3); 86 | 87 | cout << "Following is Breadth First Traversal " 88 | << "(starting from vertex 2) \n"; 89 | g.BFS(2); 90 | 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /searchingAlgo/breadthFirstSearch/BreadthFirstSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | class Graph{ 6 | private int _V; 7 | LinkedList[] _adj; 8 | 9 | public Graph(int V) 10 | { 11 | _adj = new LinkedList[V]; 12 | for(int i = 0; i < _adj.Length; i++) 13 | { 14 | _adj[i] = new LinkedList(); 15 | } 16 | _V = V; 17 | } 18 | public void AddEdge(int v, int w) 19 | { 20 | _adj[v].AddLast(w); 21 | 22 | } 23 | public void BFS(int s) 24 | { 25 | bool[] visited = new bool[_V]; 26 | for(int i = 0; i < _V; i++) 27 | visited[i] = false; 28 | LinkedList queue = new LinkedList(); 29 | visited[s] = true; 30 | queue.AddLast(s); 31 | 32 | while(queue.Any()) 33 | { 34 | s = queue.First(); 35 | Console.Write(s + " " ); 36 | queue.RemoveFirst(); 37 | LinkedList list = _adj[s]; 38 | 39 | foreach (var val in list) 40 | { 41 | if (!visited[val]) 42 | { 43 | visited[val] = true; 44 | queue.AddLast(val); 45 | } 46 | } 47 | } 48 | } 49 | static void Main(string[] args) 50 | { 51 | Graph g = new Graph(4); 52 | 53 | g.AddEdge(0, 1); 54 | g.AddEdge(0, 2); 55 | g.AddEdge(1, 2); 56 | g.AddEdge(2, 0); 57 | g.AddEdge(2, 3); 58 | g.AddEdge(3, 3); 59 | Console.Write("Following is Breadth First " + 60 | "Traversal(starting from " + 61 | "vertex 2)\n"); 62 | g.BFS(2); 63 | } 64 | } -------------------------------------------------------------------------------- /searchingAlgo/depthFirstSearch/depthFirstSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | class Graph 4 | { 5 | private int V; 6 | private List[] adj; 7 | Graph(int v) 8 | { 9 | V = v; 10 | adj = new List[v]; 11 | for (int i = 0; i < v; ++i) 12 | adj[i] = new List(); 13 | } 14 | void AddEdge(int v, int w) 15 | { 16 | adj[v].Add(w); 17 | } 18 | void DFSUtil(int v, bool[] visited) 19 | { 20 | visited[v] = true; 21 | Console.Write(v + " "); 22 | List vList = adj[v]; 23 | foreach (var n in vList) 24 | { 25 | if (!visited[n]) 26 | DFSUtil(n, visited); 27 | } 28 | } 29 | 30 | void DFS(int v) 31 | { 32 | bool[] visited = new bool[V]; 33 | DFSUtil(v, visited); 34 | } 35 | public static void Main(String[] args) 36 | { 37 | Graph g = new Graph(4); 38 | g.AddEdge(0, 1); 39 | g.AddEdge(0, 2); 40 | g.AddEdge(1, 2); 41 | g.AddEdge(2, 0); 42 | g.AddEdge(2, 3); 43 | g.AddEdge(3, 3); 44 | Console.WriteLine("Following is Depth First Traversal " + 45 | "(Starting from vertex 2)"); 46 | g.DFS(2); 47 | Console.ReadKey(); 48 | } 49 | } -------------------------------------------------------------------------------- /searchingAlgo/depthFirstSearch/depthFirstSearch.js: -------------------------------------------------------------------------------- 1 | // Graph class for the Algorithm 2 | class Graph { 3 | constructor(v) { 4 | this.V = v; 5 | this.adj = Array(v); 6 | for (let i = 0; i < v; ++i) { 7 | this.adj[i] = []; 8 | } 9 | } 10 | 11 | addEdge(v, w) { 12 | this.adj[v].push(w); 13 | } 14 | 15 | DFSUtil(v, visited) { 16 | visited[v] = true; 17 | console.log(v + " "); 18 | let vList = this.adj[v]; 19 | for (let n in vList) { 20 | if (!visited[n]) this.DFSUtil(n, visited); 21 | } 22 | } 23 | 24 | DFS(v) { 25 | let visited = new Array(this.V); 26 | this.DFSUtil(v, visited); 27 | } 28 | } 29 | 30 | function main() { 31 | let g = new Graph(4); 32 | g.addEdge(0, 1); 33 | g.addEdge(0, 2); 34 | g.addEdge(1, 2); 35 | g.addEdge(2, 0); 36 | g.addEdge(2, 3); 37 | g.addEdge(3, 3); 38 | console.log( 39 | "The Following is Depth First Traversal " + "(Starting from vertex 2)" 40 | ); 41 | g.DFS(2); 42 | } 43 | 44 | main(); 45 | -------------------------------------------------------------------------------- /searchingAlgo/depthFirstSearch/depthFirstSearch.kt: -------------------------------------------------------------------------------- 1 | /** 2 | * Creates a Graph with [size] nodes 3 | * @param init constructor for adding the edges of the nodes delegated to the instances 4 | */ 5 | class Graph(size: Int, init: Graph.() -> Unit) { 6 | val adjacency: Array> = Array(size) { ArrayList() } 7 | 8 | init { init() } 9 | 10 | fun addEdge(node: Int, to: Int) = adjacency[node].add(to) 11 | } 12 | 13 | /** 14 | * Prints the route taken when exploring the [graph] starting from [current] 15 | * @param searched an array of booleans relating to whether the relating nodes have been searched 16 | */ 17 | fun depthFirstSearch(graph: Graph, current: Int, searched: Array = Array(graph.adjacency.size) { false }) { 18 | if(!searched[current]) { 19 | searched[current] = true 20 | print("$current ") 21 | for (next in graph.adjacency[current]) { 22 | depthFirstSearch(graph, next, searched) 23 | } 24 | } 25 | } 26 | 27 | fun main() { 28 | val graph = Graph(4) { 29 | addEdge(0, 1) 30 | addEdge(0, 2) 31 | addEdge(1, 2) 32 | addEdge(2, 0) 33 | addEdge(2, 3) 34 | addEdge(3, 3) 35 | } 36 | println("Following is Depth First Traversal " + "(Starting from vertex 2)") 37 | depthFirstSearch(graph, 2) 38 | } -------------------------------------------------------------------------------- /searchingAlgo/depthFirstSearch/depthfirstsearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | 7 | class Graph //create a Graph node 8 | { 9 | int V; 10 | list *adj; 11 | void DFS_visit(int v, bool visited[]); 12 | public: 13 | Graph(int V); 14 | void addEdge(int v, int w); 15 | void DFS(int v); 16 | }; 17 | 18 | Graph::Graph(int V) //constructor 19 | { 20 | this->V = V; 21 | adj = new list[V]; 22 | } 23 | 24 | void Graph::addEdge(int v, int w) 25 | { 26 | adj[v].push_back(w); 27 | } 28 | 29 | void Graph::DFS_visit(int v, bool visited[]) 30 | { 31 | 32 | visited[v] = true; 33 | cout << v << " "; 34 | list::iterator i; 35 | for (i = adj[v].begin(); i != adj[v].end();i++) 36 | { 37 | if (!visited[*i]) 38 | DFS_visit(*i, visited); 39 | } 40 | } 41 | 42 | 43 | void Graph::DFS(int v) 44 | { 45 | // Marking all the vertices as not visited 46 | bool *visited = new bool[V]; 47 | for (int i = 0; i < V; i++) 48 | visited[i] = false; 49 | 50 | 51 | DFS_visit(v, visited); 52 | } 53 | 54 | int main() 55 | { 56 | Graph g(4); 57 | g.addEdge(0, 1); 58 | g.addEdge(0, 2); 59 | g.addEdge(1, 2); 60 | g.addEdge(2, 0); 61 | g.addEdge(2, 3); 62 | g.addEdge(3, 3); 63 | 64 | cout << "Following is Depth First Traversal \n"; 65 | int n; 66 | cin>>n; 67 | g.DFS(n); 68 | 69 | return 0; 70 | } 71 | //INPUT: 5 72 | //OUTPUT: 73 | //Following is Depth First Traversal 74 | //5 2 0 1 3 75 | -------------------------------------------------------------------------------- /searchingAlgo/exponentialSearch/README.md: -------------------------------------------------------------------------------- 1 | # Exponential Search 2 | 3 | - Exponential search allows for searching through a sorted, unbounded list for a specified input value. 4 | - Time Complexity: 5 | - Worst Case Complexity:_O_(log _i_) 6 | - Best Case Complexity:_O_(1) 7 | - Average Case Complexity:_O_(log _i_) 8 | - Worst Case Space Complexity:_O_(1) 9 | - Exponential Search will run in _O_(log _i_) time, where _i_ is the index of the element being searched for in the list, whereas binary search would run in _O_(log _n_) time, where _n_ is the number of elements in the list. 10 | - Works only on sorted lists. 11 | 12 | ### Logic 13 | 14 | 1. Find range where element is present 15 | 2. Do Binary Search in above found range. 16 | 3. Pseudo Code: 17 | 18 | function exponentialSearch(arr, x, lo, hi): 19 | if arr[hi] >= x: 20 | return(binarySearch(arr, x, lo, hi + 1)) 21 | else: 22 | return(exponentialSearch(arr, x, hi, hi * 2)) 23 | 24 | function binarySearch(arr, x, lo, hi): 25 | index = (lo + hi)/2 26 | if x = arr[index] 27 | return index 28 | else if x > arr[index]: 29 | return binarySearch(arr, x, index, hi) 30 | else: 31 | return binarySearch(arr, x, 0, index) 32 | 33 | ### Implementations 34 | 35 | - [Python](exponentialSearch.py) 36 | - [C++](exponentialSearch.cpp) 37 | 38 | ### Instruction for Running code: 39 | 40 | - Python 41 | 42 | ``` 43 | python3 exponentialSearch.py 44 | ``` 45 | 46 | - C++ 47 | 48 | For Windows 49 | 50 | ``` 51 | g++ exponentialSearch.cpp -o exponentialSearch.exe 52 | exponentialSearch.exe 53 | ``` 54 | 55 | For Linux/ Mac 56 | 57 | ``` 58 | g++ exponentialSearch.cpp -o exponentialSearch.out 59 | ./exponentialSearch.out 60 | ``` 61 | 62 | - C 63 | 64 | For Windows 65 | 66 | ``` 67 | gcc exponentialSearch.c -o exponentialSearch.exe 68 | exponentialSearch.exe 69 | ``` 70 | 71 | For Linux/Mac 72 | 73 | ``` 74 | gcc exponentialSearch.c -o exponentialSearch.out 75 | ./exponentialSearch.out 76 | ``` -------------------------------------------------------------------------------- /searchingAlgo/exponentialSearch/exponentialSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | // Function to find minimum of two given inputs 4 | int min(int a, int b) 5 | { 6 | if (a <= b) 7 | { 8 | return a; 9 | } 10 | else 11 | { 12 | return b; 13 | } 14 | } 15 | 16 | // A recursive binary search function. It returns location of x in given array a[l..r] is present, otherwise -1 17 | int binarySearch(int a[], int l, int r, int x) 18 | { 19 | if (r >= l) 20 | { 21 | int mid = l + (r - l) / 2; 22 | 23 | // If the element is present at the middle itself 24 | if (a[mid] == x) 25 | return mid; 26 | 27 | // If element is smaller than mid, then it can only be present in left subarray 28 | if (a[mid] > x) 29 | return binarySearch(a, l, mid - 1, x); 30 | 31 | // Else the element can only be present in right subarray 32 | return binarySearch(a, mid + 1, r, x); 33 | } 34 | 35 | // We reach here when element is not present in array 36 | return -1; 37 | } 38 | 39 | // Returns position of first occurrence of x in array 40 | int exponentialSearch(int a[], int n, int x) 41 | { 42 | // If x is present at firt location itself 43 | if (a[0] == x) 44 | return 0; 45 | 46 | // Find range for binary search by 47 | // repeated doubling 48 | int i = 1; 49 | while (i < n && a[i] <= x) 50 | i = i << 1; 51 | 52 | // Call binary search for the found range. 53 | return binarySearch(a, i / 2, min(i, n), x); 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | int arr[] = {2, 5, 6, 7, 9, 15, 23, 24, 89}; 60 | int n = sizeof(arr) / sizeof(arr[0]); 61 | int x = 15; 62 | int result = exponentialSearch(arr, n, x); 63 | if (result != -1) 64 | { 65 | printf("Element found at index: %d\n", result); 66 | } 67 | else 68 | { 69 | printf("Element does not exist in given array\n"); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /searchingAlgo/exponentialSearch/exponentialSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A recursive binary search function. It returns location of x in given array a[l..r] is present, otherwise -1 5 | int binarySearch(vector &a, int l, int r, int x) { 6 | if (r >= l) { 7 | int mid = l + (r - l)/2; 8 | 9 | // If the element is present at the middle itself 10 | if (a[mid] == x) 11 | return mid; 12 | 13 | // If element is smaller than mid, then it can only be present in left subarray 14 | if (a[mid] > x) 15 | return binarySearch(a, l, mid-1, x); 16 | 17 | // Else the element can only be present in right subarray 18 | return binarySearch(a, mid+1, r, x); 19 | } 20 | 21 | // We reach here when element is not present in array 22 | return -1; 23 | } 24 | 25 | // Returns position of first occurrence of x in array 26 | int exponentialSearch(vector &a, int n, int x) { 27 | // If x is present at firt location itself 28 | if (a[0] == x) 29 | return 0; 30 | 31 | // Find range for binary search by 32 | // repeated doubling 33 | int i = 1; 34 | while (i < n && a[i] <= x) 35 | i = i<<1; 36 | 37 | // Call binary search for the found range. 38 | return binarySearch(a, i/2, min(i, n), x); 39 | } 40 | 41 | 42 | 43 | 44 | // Driver code 45 | int main() { 46 | vector a = {2, 5, 6, 7, 9, 15, 23, 24, 89}; 47 | int n = a.size(); 48 | int x = 15; 49 | int result = exponentialSearch(a, n, x); 50 | if(result != -1) { 51 | cout << "\nElement found at index: " << result << '\n'; 52 | } 53 | else { 54 | cout << "\nElement not found!\n"; 55 | } 56 | } -------------------------------------------------------------------------------- /searchingAlgo/exponentialSearch/exponentialSearch.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class exponentialSearch 4 | { 5 | // Returns position of first occurrence of 6 | // x in array 7 | static int exponentialSearch(int arr[], 8 | int n, int x) 9 | { 10 | // If x is present at firt location itself 11 | if (arr[0] == x) 12 | return 0; 13 | 14 | // Find range for binary search by 15 | // repeated doubling 16 | int i = 1; 17 | while (i < n && arr[i] <= x) 18 | i = i*2; 19 | 20 | // Call binary search for the found range. 21 | return Arrays.binarySearch(arr, i/2, 22 | Math.min(i, n), x); 23 | } 24 | 25 | // Driver code 26 | public static void main(String args[]) 27 | { 28 | int arr[] = {2, 3, 4, 10, 40}; 29 | int x = 10; 30 | int result = exponentialSearch(arr, arr.length, x); 31 | 32 | System.out.println((result < 0) ? 33 | "Element is not present in array" : 34 | "Element is present at index " + 35 | result); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /searchingAlgo/exponentialSearch/exponentialSearch.py: -------------------------------------------------------------------------------- 1 | def exponentialSearch(arr, x, lo, hi): 2 | if arr[hi] >= x: 3 | return(binarySearch(arr, x, lo, hi + 1)) 4 | else: 5 | return(exponentialSearch(arr, x, hi, hi * 2)) 6 | 7 | 8 | def binarySearch(arr, x, lo, hi): # `hi` as one greater than the index of the last element present in the array 9 | idx = (lo + hi)//2 10 | 11 | if x == arr[idx]: 12 | return idx 13 | elif x > arr[idx]: 14 | return(binarySearch(arr, x, idx, hi)) 15 | else: 16 | return(binarySearch(arr, x, 0, idx)) 17 | 18 | # Testcase 19 | arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 20 | x = 2 21 | 22 | try: 23 | print(exponentialSearch(arr, x, 0, 1)) 24 | except: 25 | print(-1) 26 | -------------------------------------------------------------------------------- /searchingAlgo/fibonacciSearch/FibonacciSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class MainClass { 4 | public static void Main (string[] args) { 5 | Console.WriteLine("How big will be the array?"); 6 | int arrayLength = Convert.ToInt32(Console.ReadLine()); 7 | Console.WriteLine(); 8 | int [] array = new int[arrayLength]; 9 | int i; 10 | for (i=0; i 1) { 36 | int index = Math.Min(offset+RecursiveFibonacci(counter-2), arrayLength-1); 37 | 38 | if (array[index] < searchedNumber) { 39 | counter--; 40 | offset = index; 41 | } else if (array[index] > searchedNumber) { 42 | counter -= 2; 43 | } else return index; 44 | } 45 | 46 | if (RecursiveFibonacci(counter-1) == 1 && array[offset-1] == searchedNumber) { 47 | return offset + 1; 48 | } else return -1; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /searchingAlgo/fibonacciSearch/Fibonacci_Search.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | C++ program for Fibonacci Search 3 | */ 4 | #include 5 | using namespace std; 6 | 7 | /* 8 | Function to return the index of x in arr 9 | Time Complexity : O(logn) 10 | */ 11 | int fibMonaccianSearch(int arr[], int x, int n) 12 | { 13 | int l = 0; 14 | int r = 1; 15 | int sum = l + r; 16 | 17 | while (sum < n) { 18 | 19 | l = r; 20 | r = sum; 21 | sum = l + r; 22 | 23 | } 24 | 25 | int offset = -1; 26 | 27 | while (sum > 1) { 28 | 29 | int i = min(offset + l, n - 1); 30 | 31 | if (arr[i] < x) 32 | { 33 | sum = r; 34 | r = l; 35 | l = sum - r; 36 | offset = i; 37 | } 38 | 39 | else if (arr[i] > x) 40 | { 41 | sum = r; 42 | r = r - l; 43 | l = sum - r; 44 | } 45 | 46 | else return i; 47 | 48 | } 49 | 50 | if (l and arr[offset + 1] == x) return offset + 1; 51 | 52 | return -1; 53 | } 54 | 55 | int main() 56 | { 57 | int arr[] = {2, 3, 4, 7, 9, 13, 17, 21}; 58 | int n = sizeof(arr) / sizeof(arr[0]); 59 | int x = 13; 60 | 61 | cout << "Index of " << x << " in arr is " << fibMonaccianSearch(arr, x, n) << "\n"; 62 | 63 | return 0; 64 | } 65 | -------------------------------------------------------------------------------- /searchingAlgo/fibonacciSearch/fibonacciSearch.c: -------------------------------------------------------------------------------- 1 | /* 2 | C program for Fibonacci Search 3 | */ 4 | 5 | #include 6 | 7 | /* 8 | Function to return the index of x in arr 9 | Time Complexity : O(logn) 10 | */ 11 | 12 | int fibonacciSearch(int arr[], int x, int n) 13 | { 14 | int l = 0; 15 | int r = 1; 16 | int sum = l + r; 17 | 18 | while (sum < n) 19 | { 20 | 21 | l = r; 22 | r = sum; 23 | sum = l + r; 24 | } 25 | 26 | int offset = -1; 27 | 28 | while (sum > 1) 29 | { 30 | int i; 31 | if (offset + l < n - 1) 32 | { 33 | i = offset + l; 34 | } 35 | else 36 | { 37 | i = n - 1; 38 | } 39 | 40 | if (arr[i] < x) 41 | { 42 | sum = r; 43 | r = l; 44 | l = sum - r; 45 | offset = i; 46 | } 47 | 48 | else if (arr[i] > x) 49 | { 50 | sum = r; 51 | r = r - l; 52 | l = sum - r; 53 | } 54 | 55 | else 56 | return i; 57 | } 58 | 59 | if (l && arr[offset + 1] == x) 60 | return offset + 1; 61 | 62 | return -1; 63 | } 64 | 65 | int main() 66 | { 67 | int arr[] = {2, 3, 4, 7, 9, 13, 17, 21}; 68 | int n = sizeof(arr) / sizeof(arr[0]); 69 | int x = 13; 70 | 71 | printf("Index of %d in arr is %d\n", x, fibonacciSearch(arr, x, n)); 72 | 73 | return 0; 74 | } 75 | -------------------------------------------------------------------------------- /searchingAlgo/fibonacciSearch/fibonacciSearch.py: -------------------------------------------------------------------------------- 1 | from bisect import bisect_left 2 | 3 | # Returns index of x if present, else 4 | # returns -1 5 | def fibonacciSearch(arr, x, n): 6 | 7 | # Initialize fibonacci numbers 8 | fibMMm2 = 0 9 | fibMMm1 = 1 10 | fibM = fibMMm2 + fibMMm1 11 | 12 | # fibM is going to store the smallest 13 | # Fibonacci Number greater than or equal to n 14 | while (fibM < n): 15 | fibMMm2 = fibMMm1 16 | fibMMm1 = fibM 17 | fibM = fibMMm2 + fibMMm1 18 | 19 | # Marks the eliminated range from front 20 | offset = -1; 21 | 22 | # Note that we compare arr[fibMm2] with x. 23 | # When fibM becomes 1, fibMm2 becomes 0 24 | while (fibM > 1): 25 | 26 | # Check if fibMm2 is a valid location 27 | i = min(offset+fibMMm2, n-1) 28 | 29 | # If x is greater than the value at 30 | # index fibMm2, cut the subarray array 31 | # from offset to i 32 | if (arr[i] < x): 33 | fibM = fibMMm1 34 | fibMMm1 = fibMMm2 35 | fibMMm2 = fibM - fibMMm1 36 | offset = i 37 | 38 | # If x is less than the value at 39 | # index fibMm2, cut the subarray 40 | # after i+1 41 | elif (arr[i] > x): 42 | fibM = fibMMm2 43 | fibMMm1 = fibMMm1 - fibMMm2 44 | fibMMm2 = fibM - fibMMm1 45 | 46 | # element found. return index 47 | else : 48 | return i 49 | 50 | # comparing the last element with x */ 51 | if(fibMMm1 and arr[offset+1] == x): 52 | return offset+1; 53 | 54 | # element not found. return -1 55 | return -1 56 | 57 | # Driver Code 58 | arr = [10, 22, 35, 40, 45, 50, 59 | 80, 82, 85, 90, 100] 60 | n = len(arr) 61 | x = 85 62 | print("Found at index:", 63 | fibonacciSearch(arr, x, n)) -------------------------------------------------------------------------------- /searchingAlgo/fibonacciSearch/fibonacciSearch.py.py: -------------------------------------------------------------------------------- 1 | # return the fibonacci number at the index of n 2 | def FibonacciGenerator(n): 3 | if n < 1: 4 | return 0 5 | elif n == 1: 6 | return 1 7 | else: 8 | return FibonacciGenerator(n - 1) + FibonacciGenerator(n - 2) 9 | 10 | # return the index at which x exists inside arr 11 | # return -1 otherwise 12 | 13 | def FibonacciSearch(arr, x): 14 | 15 | # find the smallest Fibonacci number greater than or equal 16 | # to the length of arr 17 | m = 0 18 | while FibonacciGenerator(m) < len(arr): # 19 | m = m + 1 20 | 21 | offset = -1 22 | while (FibonacciGenerator(m) > 1): 23 | 24 | i = min( offset + FibonacciGenerator(m - 2) , len(arr) - 1) 25 | 26 | if (x > arr[i]): 27 | 28 | m = m - 1 29 | offset = i 30 | 31 | elif (x < arr[i]): 32 | 33 | m = m - 2 34 | 35 | else: 36 | 37 | return i 38 | 39 | # this will run if there is one last element left 40 | if(FibonacciGenerator(m - 1) and arr[offset + 1] == x): 41 | return offset + 1 42 | 43 | # return -1 if the element doesn't exist in the array 44 | return -1 45 | 46 | 47 | # the search array 48 | print("Enter array : ", end='') 49 | arr = list(map(int, input().split())) 50 | 51 | x = int(input("Enter number to be searched : ")) 52 | #if array is not sorted. 53 | print(FibonacciSearch(sorted(arr), x)) 54 | #if array is sorted 55 | #print(FibonacciSearch(arr, x)) -------------------------------------------------------------------------------- /searchingAlgo/interpolationSearch/interpolationSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | /** 5 | * Interpolation search function. 6 | * 7 | * @param v Sorted vector on which the search will be performed. 8 | * @param x Element to be searched. 9 | * @return Element index if found; -1 otherwise. 10 | */ 11 | int interpolationSearch(const std::vector &v, long int x) { 12 | int lo = 0; // first index 13 | int hi = v.size() - 1; // last index 14 | 15 | while(lo <= hi && x >= v[lo] && x <= v[hi]) { 16 | if(lo == hi) { 17 | if(v[lo] == x) return lo; 18 | return -1; 19 | } 20 | 21 | // standard algorithm formula 22 | // pos is a higher value when the searched element is closer to v[hi] 23 | // pos is a lower value when the searched element is closer to v[lo] 24 | int pos = lo + (((double)(hi - lo)/(v[hi] - v[lo])) * (x - v[lo])); 25 | 26 | if(v[pos] == x) return pos; // found 27 | 28 | if(v[pos] < x) lo = pos + 1; // x is in upper part 29 | else hi = pos - 1; // x is in lower part 30 | } 31 | 32 | return -1; // not found 33 | } 34 | 35 | /** 36 | * Driver code. 37 | */ 38 | int main() { 39 | // sorted vector on which the search will be performed; [0, 30] 40 | std::vector v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}; 41 | long int x = 7; // element to be searched 42 | int index = interpolationSearch(v, x); 43 | 44 | if(index != -1) std::cout << "Element found at index " << index; 45 | else std::cout << "Element not found"; 46 | std::cout << std::endl; 47 | 48 | return 0; 49 | } -------------------------------------------------------------------------------- /searchingAlgo/interpolationSearch/interpolationSearch.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def search(arr, x, lo, hi): 4 | pos = math.ceil(lo + ((x - arr[lo]) * (hi - lo) / (arr[hi] - arr[lo]))) 5 | if arr[pos] == x: 6 | return pos 7 | elif arr[pos] > x: 8 | return search(arr, x, lo, pos - 1) 9 | else: 10 | return search(arr, x, pos + 1, hi) 11 | 12 | # Testcase 13 | arr = [0, 1, 2, 3, 4, 5, 6, , 7, 8, 9] 14 | x = 2 15 | 16 | try: 17 | print(search(arr, x, 0, len(arr) - 1)) 18 | except: 19 | print(-1) 20 | -------------------------------------------------------------------------------- /searchingAlgo/jumpSearch/jumpSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | /** 7 | * Jump search function. 8 | * 9 | * @param v Sorted vector on which the search will be performed. 10 | * @param x Element to be searched. 11 | * @return Element index if found; -1 otherwise. 12 | */ 13 | int jumpSearch(const std::vector &v, long int x) { 14 | int n = v.size(); // number of elements 15 | int jump = std::sqrt(n); // block size to jump 16 | 17 | // search for the block the element may be in 18 | int prev = 0; 19 | while(jump < n && v[jump] <= x) { 20 | prev = jump; // jump to next block 21 | jump += std::sqrt(n); 22 | if(prev >= n) return -1; // vector size exceeded 23 | } 24 | 25 | // linear search through the block 26 | while(prev < jump) { 27 | if(v[prev] == x) return prev; // element found 28 | prev++; 29 | } 30 | 31 | return -1; // not found 32 | } 33 | 34 | /** 35 | * Driver code. 36 | */ 37 | int main() { 38 | // sorted vector on which the search will be performed; [0, 30] 39 | std::vector v = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}; 40 | long int x = 7; // element to be searched 41 | int index = jumpSearch(v, x); 42 | 43 | if(index != -1) std::cout << "Element found at index " << index; 44 | else std::cout << "Element not found"; 45 | std::cout << std::endl; 46 | 47 | return 0; 48 | } -------------------------------------------------------------------------------- /searchingAlgo/jumpSearch/jumpSearch.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def jumpSearch(arr, x): 4 | l = len(arr) 5 | step = math.floor(math.sqrt(l)) 6 | for i in range(0, l - 1, step): 7 | if arr[i] > x: 8 | return(linearSearch(arr[(i - step):i], x, (i - step))) 9 | return -1 10 | 11 | 12 | def linearSearch(arr, x, minIndex): 13 | for i, val in enumerate(arr): 14 | if val == x: 15 | return i + minIndex 16 | 17 | return -1 18 | 19 | # Testcase 20 | arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 21 | x = 2 22 | 23 | print(jumpSearch(arr, x)) 24 | -------------------------------------------------------------------------------- /searchingAlgo/kmpSearch/kmpSearch.py: -------------------------------------------------------------------------------- 1 | def KMPSearch(pat, txt): 2 | M = len(pat) 3 | N = len(txt) 4 | 5 | lps = [0]*M 6 | j = 0 7 | 8 | computeLPSArray(pat, M, lps) 9 | 10 | i = 0 11 | while i < N: 12 | if pat[j] == txt[i]: 13 | i += 1 14 | j += 1 15 | 16 | if j == M: 17 | print "Found pattern at index " + str(i-j) 18 | j = lps[j-1] 19 | 20 | 21 | elif i < N and pat[j] != txt[i]: 22 | if j != 0: 23 | j = lps[j-1] 24 | else: 25 | i += 1 26 | 27 | def computeLPSArray(pat, M, lps): 28 | len = 0 29 | 30 | lps[0] 31 | i = 1 32 | 33 | while i < M: 34 | if pat[i]== pat[len]: 35 | len += 1 36 | lps[i] = len 37 | i += 1 38 | else: 39 | if len != 0: 40 | len = lps[len-1] 41 | 42 | else: 43 | lps[i] = 0 44 | i += 1 45 | 46 | # Testcase 47 | txt = "ABABDABACDABABCABAB" 48 | pat = "ABABCABAB" 49 | KMPSearch(pat, txt) -------------------------------------------------------------------------------- /searchingAlgo/linearSearch/README.md: -------------------------------------------------------------------------------- 1 | # Linear Search 2 | 3 | - Searches For an Element by Traversing through the entire list. 4 | - Time Complexity: 5 | - Worst Case Complexity:O(n) 6 | - Best Case Complexity:O(1) 7 | - Average Case Complexity:O(n/2) 8 | - Worst Case Space Complexity:O(1) 9 | 10 | ### Logic 11 | 12 | 1. Iterate through Each Element and compare each Element till you find the element. 13 | 2. If element is found,return the index. 14 | 3. Otherwise return -1 or False representing that element is not found. 15 | 4. Pseudo Code: 16 | 17 | function linear_search(list,n) 18 | let i ← 0 19 | while i < len(list) 20 | if element = n 21 | return i 22 | return -1 23 | 24 | ### Instruction for Running code: 25 | - C 26 | ``` 27 | gcc LinearSearch.c 28 | ./a.out 29 | ``` 30 | 31 | - Cpp 32 | ``` 33 | g++ LinearSearch.cpp 34 | ./a.out 35 | ``` 36 | - JavaScript 37 | ``` 38 | node LinearSearch.js 39 | ``` 40 | - Python 41 | ``` 42 | python3 LinearSearch.py 43 | ``` 44 | -------------------------------------------------------------------------------- /searchingAlgo/linearSearch/linearSearch.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | int search(char* arr[], int lgt, char* x); 5 | 6 | int main(void) { 7 | 8 | // Testcase 9 | char* arr[] = {"a", "b", "c", "d"}; 10 | char* x = "b"; 11 | 12 | 13 | int lgt = sizeof(arr)/sizeof(arr[0]); 14 | printf("%i\n", search(arr, lgt, x)); 15 | } 16 | 17 | 18 | int search(char* arr[], int lgt, char* x) { 19 | for(int i = 0; i < lgt; i++){ 20 | if (arr[i] == x){ 21 | return i; 22 | } 23 | } 24 | return -1; 25 | } 26 | -------------------------------------------------------------------------------- /searchingAlgo/linearSearch/linearSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int search(int arr[], int n, int x) 5 | { 6 | int i; 7 | for (i = 0; i < n; i++) 8 | if (arr[i] == x) 9 | return i; 10 | return -1; 11 | } 12 | 13 | int main(void) 14 | { 15 | int arr[] = { 2, 3, 4, 10, 40 }; 16 | int x = 10; 17 | int n = sizeof(arr) / sizeof(arr[0]); 18 | int result = search(arr, n, x); 19 | (result == -1)? cout<<"Element is not present in array" 20 | : cout<<"Element is present at index " < 2 | #include 3 | 4 | 5 | int rabinKarp(char txt[], char pat[], int q) 6 | { 7 | int txt_len = strlen(txt); 8 | int pat_len = strlen(pat); 9 | int d = 256; 10 | int p=0,t=0,h=1; 11 | 12 | for(int i=0;i 2 | using namespace std; 3 | 4 | 5 | int rabinKarp(string txt, string pat, int q) 6 | { 7 | int txt_len = txt.length(); 8 | int pat_len = pat.length(); 9 | int d = 256; 10 | int p=0,t=0,h=1; 11 | 12 | for(int i=0;i 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | bool findList(Node* first, Node* second) 11 | { 12 | Node* ptr1 = first, *ptr2 = second; 13 | 14 | if (first == NULL && second == NULL) 15 | return true; 16 | 17 | if ( first == NULL || 18 | (first != NULL && second == NULL)) 19 | return false; 20 | 21 | while (second != NULL) 22 | { 23 | ptr2 = second; 24 | while (ptr1 != NULL) 25 | { 26 | if (ptr2 == NULL) 27 | return false; 28 | 29 | else if (ptr1->data == ptr2->data) 30 | { 31 | ptr1 = ptr1->next; 32 | ptr2 = ptr2->next; 33 | } 34 | 35 | else break; 36 | } 37 | 38 | if (ptr1 == NULL) 39 | return true; 40 | ptr1 = first; 41 | second = second->next; 42 | } 43 | 44 | return false; 45 | } 46 | 47 | void printList(Node* node) 48 | { 49 | while (node != NULL) 50 | { 51 | printf("%d ", node->data); 52 | node = node->next; 53 | } 54 | } 55 | 56 | Node *newNode(int key) 57 | { 58 | Node *temp = new Node; 59 | temp-> data= key; 60 | temp->next = NULL; 61 | return temp; 62 | } 63 | 64 | /* Driver program to test above functions*/ 65 | int main() 66 | { 67 | Node *a = newNode(1); 68 | a->next = newNode(2); 69 | a->next->next = newNode(3); 70 | a->next->next->next = newNode(4); 71 | 72 | Node *b = newNode(1); 73 | b->next = newNode(2); 74 | b->next->next = newNode(1); 75 | b->next->next->next = newNode(2); 76 | b->next->next->next->next = newNode(3); 77 | b->next->next->next->next->next = newNode(4); 78 | 79 | findList(a,b) ? cout << "LIST FOUND" : 80 | cout << "LIST NOT FOUND"; 81 | 82 | return 0; 83 | } 84 | -------------------------------------------------------------------------------- /searchingAlgo/sublistSearch/sublistSearch.java: -------------------------------------------------------------------------------- 1 | package searchingAlgo.sublistSearch; 2 | 3 | class Node { 4 | int data; 5 | String sdata; 6 | Node next; 7 | Node(int d) { 8 | data = d; 9 | next = null; 10 | } 11 | } 12 | 13 | public class sublistSearch { 14 | public static boolean sublistSearch(Node subList, Node list) { 15 | if(subList == null && list == null) { 16 | return true; 17 | }else if (subList == null || (subList != null && list == null)) { 18 | return false; 19 | } 20 | 21 | Node curr1 = subList; 22 | Node curr2 = list; 23 | 24 | while(list != null) { 25 | curr2 = list; 26 | while(curr1 != null) { 27 | if (curr2 == null) { 28 | return false; 29 | } 30 | if (curr1.data == curr2.data) { 31 | curr1 = curr1.next; 32 | curr2 = curr2.next; 33 | }else { 34 | break; 35 | } 36 | 37 | 38 | } 39 | if (curr1 == null) { 40 | return true; 41 | } 42 | curr1 = subList; 43 | list = list.next; 44 | 45 | } 46 | return false; 47 | 48 | 49 | } 50 | 51 | public static void main(String[] args) { 52 | Node subList1 = new Node(1); 53 | subList1.next = new Node(2); 54 | 55 | Node subList2 = new Node(2); 56 | subList2.next = new Node(3); 57 | 58 | Node list = new Node(1); 59 | list.next = new Node(2); 60 | list.next.next = new Node(4); 61 | 62 | System.out.println(sublistSearch(subList1,list)); 63 | System.out.println(sublistSearch(subList2,list)); 64 | 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /searchingAlgo/sublistSearch/sublistSearch.py: -------------------------------------------------------------------------------- 1 | # Python3 code to demonstrate 2 | # to check if list is subset of other 3 | # using all() 4 | 5 | # initializing list 6 | test_list = [int(item) for item in input("Enter the first list items : ").split()] 7 | 8 | sub_list = [int(item) for item in input("Enter the second list items : ").split()] 9 | 10 | 11 | 12 | # using all() to 13 | # check subset of list 14 | flag = 0 15 | if (all(x in test_list for x in sub_list)): 16 | flag = 1 17 | 18 | # printing result 19 | if (flag): 20 | print("Yes, list is subset of other.") 21 | else: 22 | print("No, list is not subset of other.") 23 | -------------------------------------------------------------------------------- /searchingAlgo/ternarySearch/ternarySearch.py: -------------------------------------------------------------------------------- 1 | def ternarySearch(arr, x, lo, hi): 2 | mid1 = lo + (hi - lo)//3 3 | mid2 = lo + 2 * (hi - lo)//3 4 | 5 | if x < arr[mid1]: 6 | return(ternarySearch(arr, x, 0, mid1)) 7 | elif x == arr[mid1]: 8 | return mid1 9 | elif x < arr[mid2]: 10 | return ternarySearch(arr, x, mid1 + 1, mid2) 11 | elif x == arr[mid2]: 12 | return mid2 13 | else: 14 | return ternarySearch(arr, x, mid2 + 1, hi) 15 | 16 | # Testcase 17 | arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 18 | x = 2 19 | 20 | try: 21 | print(ternarySearch(arr, x, 0, len(arr))) 22 | except: 23 | print(-1) 24 | -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/Readme.md: -------------------------------------------------------------------------------- 1 | ## Bubble Sort 2 | Bubble sort is an algorithm that compares the adjacent elements and swaps their positions 3 | if they are not in the intended order. The order can be ascending or descending. 4 | 5 | bubbleSort(array) 6 | swapped <- false 7 | for i <- 1 to indexOfLastUnsortedElement-1 8 | if leftElement > rightElement 9 | swap leftElement and rightElement 10 | swapped <- true 11 | end bubbleSort 12 | 13 | ## Complexity 14 | Bubble Sort is one of the simplest sorting algorithms. Two loops are implemented in the algorithm. 15 | ### Time Complexities: 16 | * #### Worst Case Complexity: O(n2) 17 | If we want to sort in ascending order and the array is in descending order then, the worst case occurs. 18 | * #### Best Case Complexities: O(n) 19 | If the array is already sorted, then there is no need for sorting. 20 | * #### Average Case Complexity: O(n2) 21 | It occurs when the elements of the array are in jumbled order (neither ascending nor descending). 22 | 23 | ### Space Complexity: 24 | Space Complexity is **O(2)** because the variable swapped adds to the space complexity. 25 | ### Bubble Sort Applications: 26 | It is used in the following cases where 27 | 1. the complexity of the code does not matter. 28 | 2. a short code is preffered. 29 | 30 | ### Instruction for Running code: 31 | 32 | - Cpp 33 | ``` 34 | g++ bubbleSort.cpp
35 | ./a.out 36 | ``` 37 | - Python 38 | ``` 39 | python3 bubbleSort\.py 40 | ``` 41 | - C 42 | ``` 43 | gcc bubbleSort.c 44 | ./a.out 45 | ``` 46 | - Java 47 | ``` 48 | javac bubbleSort.java 49 | java bubbleSort 50 | ``` 51 | - JavaScript 52 | ``` 53 | node bubbleSort.js 54 | ``` 55 | -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | 4 | // Function to swap the values of 2 int variables 5 | void swap(int a, int b) 6 | { 7 | int temp = a; 8 | a = b; 9 | b = temp; 10 | } 11 | 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | for (i = 0; i < n - 1; i++) 16 | 17 | // Last i elements are already in place 18 | for (j = 0; j < n - i - 1; j++) 19 | { 20 | if (arr[j] > arr[j + 1]) 21 | { 22 | swap(arr[j], arr[j + 1]); 23 | } 24 | } 25 | } 26 | 27 | void printArray(int arr[], int size) 28 | { 29 | int i; 30 | for (i = 0; i < size; i++) 31 | { 32 | printf("%d ", arr[i]); 33 | } 34 | printf("\n"); 35 | } 36 | 37 | int main() 38 | { 39 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 40 | int n = sizeof(arr) / sizeof(arr[0]); 41 | bubbleSort(arr, n); 42 | printf("Sorted array: \n"); 43 | printArray(arr, n); 44 | return 0; 45 | } -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | void bubbleSort(int arr[], int n) 12 | { 13 | int i, j; 14 | for (i = 0; i < n-1; i++) 15 | 16 | // Last i elements are already in place 17 | for (j = 0; j < n-i-1; j++) 18 | if (arr[j] > arr[j+1]) 19 | swap(&arr[j], &arr[j+1]); 20 | } 21 | 22 | void printArray(int arr[], int size) 23 | { 24 | int i; 25 | for (i = 0; i < size; i++) 26 | cout << arr[i] << " "; 27 | cout << endl; 28 | } 29 | 30 | int main() 31 | { 32 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 33 | int n = sizeof(arr)/sizeof(arr[0]); 34 | bubbleSort(arr, n); 35 | cout<<"Sorted array: \n"; 36 | printArray(arr, n); 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class bubbleSort { 4 | 5 | public static void bubbleSort(int[] arr) { 6 | int temp; 7 | for (int i = 0; i < arr.length-1; i++) { 8 | for (int j = 0; j < arr.length-1-i; j++) { 9 | if (arr[j] > arr[j+1]) { 10 | temp = arr[j]; 11 | arr[j] = arr[j+1]; 12 | arr[j+1] = temp; 13 | } 14 | } 15 | } 16 | } 17 | 18 | public static void main(String[] args) { 19 | int[] arr = new int[]{1, 31, 3, 3, 8, 71, 28, 37, 71, 33, 10, 40}; 20 | bubbleSort(arr); 21 | System.out.println(Arrays.toString(arr)); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.js: -------------------------------------------------------------------------------- 1 | // This function will return the sorted array given in arguments! 2 | 3 | function bubbleSort(arr) { 4 | for(let i = 0; i < arr.length; i++) { 5 | for(let j = 0; j < arr.length; j ++) { 6 | let pos1 = arr[j]; 7 | let pos2 = arr[j+1]; 8 | 9 | if(arr[j] > arr[j+1]) { 10 | arr[j+1] = pos1; 11 | arr[j] = pos2; 12 | } 13 | } 14 | return arr; 15 | } 16 | } 17 | console.log(bubbleSort([4, 5, 9, 3])); // Output: [9, 5, 4, 3] 18 | -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the bubble sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function bubbleSort(t) 5 | local n = #t 6 | for i = 1, n do 7 | for j = 1, n - i do 8 | if t[j] > t[j + 1] then 9 | t[j], t[j + 1] = t[j + 1], t[j] 10 | end 11 | end 12 | end 13 | end 14 | 15 | --[[ 16 | local t = { 3, 2, 1, 4, 5, 6, 7, 8, 9, 10 } 17 | bubbleSort(t) 18 | print(table.concat(t, ", ")) 19 | ]] 20 | 21 | return bubbleSort -------------------------------------------------------------------------------- /sortingAlgo/bubbleSort/bubbleSort.py: -------------------------------------------------------------------------------- 1 | def bubbleSort(arr): 2 | n = len(arr) 3 | 4 | for i in range(n - 1): 5 | swapped = False # Flag to track swaps in a pass. 6 | 7 | for j in range(0, n - i - 1): 8 | if arr[j] > arr[j + 1]: # If elements are in the wrong order, swap them. 9 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 10 | swapped = True 11 | 12 | if not swapped: # If no swaps occurred in this pass, the list is already sorted. 13 | break 14 | 15 | return arr 16 | 17 | arr = [1, 63, 103, 3, 8, 74, 76, 37, 71, 66] 18 | sorted_arr = bubbleSort(arr) 19 | print(sorted_arr) 20 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/BucketSort.cpp: -------------------------------------------------------------------------------- 1 | // Bucket Sort in cpp 2 | 3 | #include 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | void print_vec(vector vec) { 10 | for(int i = 0; i&vec) { 17 | int size = vec.size(); 18 | vector bucket[size]; 19 | 20 | // put elements into different buckets 21 | for(int i = 0; i v(10); 41 | v = {0.542, 0.512, 0.761, 0.123, 0.541, .0981, 0.841, 0.01, 0.7, 0.901}; 42 | 43 | cout << "Array before Sorting: "; 44 | print_vec(v); 45 | bucketSort(v); 46 | 47 | cout << "Array after Sorting: "; 48 | print_vec(v); 49 | } 50 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/BucketSort.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | 4 | 5 | class BucketSort { 6 | 7 | 8 | static void bucketSort(int arr[], int n) 9 | { 10 | if (n <= 0) 11 | return; 12 | 13 | 14 | @SuppressWarnings("unchecked") 15 | Vector[] buckets = new Vector[n]; 16 | 17 | for (int i = 0; i < n; i++) { 18 | buckets[i] = new Vector(); 19 | } 20 | 21 | 22 | for (int i = 0; i < n; i++) { 23 | float idx = arr[i] * n; 24 | buckets[(int)idx].add(arr[i]); 25 | } 26 | 27 | 28 | for (int i = 0; i < n; i++) { 29 | Collections.sort(buckets[i]); 30 | } 31 | 32 | 33 | int index = 0; 34 | for (int i = 0; i < n; i++) { 35 | for (int j = 0; j < buckets[i].size(); j++) { 36 | arr[index++] = buckets[i].get(j); 37 | } 38 | } 39 | } 40 | 41 | 42 | public static void main(String args[]) 43 | { 44 | int arr[] = {10,14,8,78,4,66,542,22,14}; 45 | 46 | int n = arr.length; 47 | bucketSort(arr, n); 48 | 49 | System.out.println("Sorted array is "); 50 | for (int el : arr) { 51 | System.out.print(el + " "); 52 | } 53 | } 54 | } 55 | 56 | 57 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/BucketSort.py: -------------------------------------------------------------------------------- 1 | # using bucket sort 2 | def insertionSort(b): 3 | for i in range(1, len(b)): 4 | up = b[i] 5 | j = i - 1 6 | while j >= 0 and b[j] > up: 7 | b[j + 1] = b[j] 8 | j -= 1 9 | b[j + 1] = up 10 | return b 11 | 12 | def bucketSort(x): 13 | arr = [] 14 | slot_num = 10 15 | for i in range(slot_num): 16 | arr.append([]) 17 | 18 | for j in x: 19 | index_b = int(slot_num * j) 20 | arr[index_b].append(j) 21 | 22 | # Sort individual buckets 23 | for i in range(slot_num): 24 | arr[i] = insertionSort(arr[i]) 25 | 26 | # concatenate the result 27 | k = 0 28 | for i in range(slot_num): 29 | for j in range(len(arr[i])): 30 | x[k] = arr[i][j] 31 | k += 1 32 | return x 33 | 34 | # Driver Code 35 | x = [0.897, 0.565, 0.656, 36 | 0.1234, 0.665, 0.3434] 37 | print("Sorted Array is") 38 | print(bucketSort(x)) 39 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/Readme.md: -------------------------------------------------------------------------------- 1 | ## Bucket Sort 2 | 3 | Bucket Sort is a sorting technique that sorts the elements by first dividing the elements into several groups called **buckets**. The elements inside each **bucket** are sorted using any of the suitable sorting algorithms or recursively calling the same algorithm. 4 | 5 | The process of bucket sort can be understood as **a scatter-gather** approach. The elements are first scattered into buckets then the elements of buckets are sorted. Finally, the elements are gathered in order. 6 | 7 | bucketSort() 8 | create N buckets each of which can hold a range of values 9 | for all the buckets 10 | initialize each bucket with 0 values 11 | for all the buckets 12 | put elements into buckets matching the range 13 | for all the buckets 14 | sort elements in each bucket 15 | gather elements from each bucket 16 | end bucketSort 17 | 18 | ## Complexity 19 | Shell sort is an unstable sorting algorithm because this algorithm does not examine the elements lying in between the intervals. 20 | ### Time Complexities: 21 | * #### Worst Case Complexity: O(n2) 22 | When there are elements of close range in the array, they are likely to be placed in the same bucket. This may result in some buckets having more number of elements than others. 23 | It makes the complexity depend on the sorting algorithm used to sort the elements of the bucket. 24 | The complexity becomes even worse when the elements are in reverse order. 25 | * #### Best Case Complexities: O(n+k) 26 | It occurs when the elements are uniformly distributed in the buckets with a nearly equal number of elements in each bucket. 27 | The complexity becomes even better if the elements inside the buckets are already sorted. 28 | * #### Average Case Complexity: O(n) 29 | It occurs when the elements are distributed randomly in the array. Even if the elements are not distributed uniformly, bucket sort runs in linear time. 30 | 31 | ### Bucket Sort Applications: 32 | Bucket sort is used when 33 | 1. Input is uniformly distributed over a range. 34 | 2. There are floating point values. 35 | 36 | ### Instruction for Running code: 37 | - C 38 | ``` 39 | gcc BucketSort.c 40 | ./a.out 41 | ``` 42 | - Cpp 43 | 44 | ```` 45 | g++ BucketSort.cpp 46 | ./a.out 47 | ```` 48 | - Java 49 | 50 | ``` 51 | javac BucketSort.java 52 | java BucketSort.class 53 | ``` 54 | - Python 55 | ``` 56 | python3 BucketSort.py 57 | ``` 58 | 59 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/bucketSort.js: -------------------------------------------------------------------------------- 1 | // InsertionSort to be used within bucket sort 2 | function insertionSort(array) { 3 | var length = array.length; 4 | 5 | for(var i = 1; i < length; i++) { 6 | var temp = array[i]; 7 | for(var j = i - 1; j >= 0 && array[j] > temp; j--) { 8 | array[j+1] = array[j]; 9 | } 10 | array[j+1] = temp; 11 | } 12 | 13 | return array; 14 | } 15 | 16 | // Implement bucket sort 17 | function bucketSort(array, bucketSize) { 18 | if (array.length === 0) { 19 | return array; 20 | } 21 | 22 | // Declaring vars 23 | var i, 24 | minValue = array[0], 25 | maxValue = array[0], 26 | bucketSize = bucketSize || 5; 27 | 28 | // Setting min and max values 29 | array.forEach(function (currentVal) { 30 | if (currentVal < minValue) { 31 | minValue = currentVal; 32 | } else if (currentVal > maxValue) { 33 | maxValue = currentVal; 34 | } 35 | }) 36 | 37 | // Initializing buckets 38 | var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; 39 | var allBuckets = new Array(bucketCount); 40 | 41 | for (i = 0; i < allBuckets.length; i++) { 42 | allBuckets[i] = []; 43 | } 44 | 45 | // Pushing values to buckets 46 | array.forEach(function (currentVal) { 47 | allBuckets[Math.floor((currentVal - minValue) / bucketSize)].push(currentVal); 48 | }); 49 | 50 | // Sorting buckets 51 | array.length = 0; 52 | 53 | allBuckets.forEach(function(bucket) { 54 | insertionSort(bucket); 55 | bucket.forEach(function (element) { 56 | array.push(element) 57 | }); 58 | }); 59 | 60 | return array; 61 | } 62 | -------------------------------------------------------------------------------- /sortingAlgo/bucketsort/bucketSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the bucket sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function bucketSort(t) 5 | local n = #t 6 | local buckets = {} 7 | for i = 1, n do 8 | local bucket = math.floor(n * t[i]) 9 | buckets[bucket] = buckets[bucket] or {} 10 | table.insert(buckets[bucket], t[i]) 11 | end 12 | for i = 1, n do 13 | if buckets[i] then 14 | table.sort(buckets[i]) 15 | end 16 | end 17 | local k = 1 18 | for i = 1, n do 19 | if buckets[i] then 20 | for j = 1, #buckets[i] do 21 | t[k] = buckets[i][j] 22 | k = k + 1 23 | end 24 | end 25 | end 26 | return t 27 | end 28 | 29 | return bucketSort -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void cocktail_sort(int *arr, int length) 4 | { 5 | int start = 0, end = length - 1, flag = 1, temp; 6 | while (flag) 7 | { 8 | flag = 0; 9 | for (int i = start; i < end; i++) 10 | { 11 | if (arr[i] > arr[i + 1]) 12 | { 13 | temp = arr[i]; 14 | arr[i] = arr[i + 1]; 15 | arr[i + 1] = temp; 16 | flag = 1; 17 | } 18 | } 19 | if (!flag) 20 | break; 21 | flag = 0; 22 | end--; 23 | for (int i = end - 1; i >= start; i--) 24 | { 25 | if (arr[i] > arr[i + 1]) 26 | { 27 | temp = arr[i]; 28 | arr[i] = arr[i + 1]; 29 | arr[i + 1] = temp; 30 | flag = 1; 31 | } 32 | } 33 | start++; 34 | } 35 | } 36 | 37 | void main() 38 | { 39 | int arr[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40}, size = sizeof(arr) / sizeof(arr[0]); 40 | printf("array before: "); 41 | for (int i = 0; i < size; i++) 42 | { 43 | printf("%d, ", arr[i]); 44 | } 45 | printf("\nperforming cocktail sort..."); 46 | cocktail_sort(arr, size); 47 | printf("\narray after: "); 48 | for (int i = 0; i < size; i++) 49 | { 50 | printf("%d, ", arr[i]); 51 | } 52 | printf("\n"); 53 | } -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void cocktailSort(int arr[], int n){ 4 | bool flag = true; 5 | int start = 0, end = n-1; 6 | while(flag){ 7 | flag = false; 8 | for(int i = start; i arr[i+1]){ 10 | swap(arr[i], arr[i+1]); 11 | flag = true; 12 | } 13 | } 14 | if(!flag){ //if nothing has changed simply break the loop 15 | break; 16 | } 17 | flag = false; 18 | end--; //decrease the end pointer 19 | for(int i = end - 1; i >= start; i--){ //scan from right to left 20 | if(arr[i] > arr[i+1]){ 21 | swap(arr[i], arr[i+1]); 22 | flag = true; 23 | } 24 | } 25 | start++; 26 | } 27 | } 28 | main() { 29 | int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40}; 30 | int n = sizeof(data)/sizeof(data[0]); 31 | cout << "Sorted Sequence "; 32 | cocktailSort(data, n); 33 | for(int i = 0; i arr[i+1] { 12 | arr[i], arr[i+1] = arr[i+1], arr[i] 13 | swapped = true 14 | } 15 | } 16 | // if they are no changes in the entire iteration, 17 | // this means that the algorithm has ended 18 | if !swapped { 19 | break 20 | } 21 | } 22 | } 23 | 24 | func main() { 25 | 26 | // user input 27 | fmt.Printf("Enter number of elements in array: ") 28 | var n int 29 | fmt.Scanf("%d", &n) 30 | 31 | fmt.Printf("Enter the array: ") 32 | var arr []int 33 | for i := 0; i < n; i++ { 34 | var k int 35 | fmt.Scanf("%d", &k) 36 | arr = append(arr, k) 37 | } 38 | 39 | cocktailSort(arr) 40 | 41 | fmt.Printf("Sorted array: %v\n", arr) 42 | } 43 | -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailSort.js: -------------------------------------------------------------------------------- 1 | function cocktailSort(array) { 2 | 3 | var n = array.length; 4 | 5 | var isSorted = false; 6 | 7 | while (!isSorted) { 8 | isSorted = true; 9 | 10 | for (var i = 0; i < n - 1; i++) { 11 | if (array[i] > array[i + 1]) { 12 | var temp = array[i]; 13 | array[i] = array[i + 1]; 14 | array[i + 1] = temp; 15 | isSorted = false; 16 | } 17 | } 18 | 19 | if (isSorted) { 20 | break; 21 | } 22 | 23 | isSorted = true; 24 | 25 | for (var j = n - 1; j > 0; j--) { 26 | if (array[j - 1] > array[j]) { 27 | var temp = array[j]; 28 | array[j] = array[j + 1]; 29 | array[j + 1] = temp; 30 | isSorted = false; 31 | } 32 | } 33 | } 34 | 35 | return array; 36 | } 37 | -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the cocktail sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function cocktailSort(t) 5 | local n = #t 6 | local swapped = true 7 | local start = 1 8 | local end_ = n - 1 9 | while swapped do 10 | swapped = false 11 | for i = start, end_ do 12 | if t[i] > t[i + 1] then 13 | t[i], t[i + 1] = t[i + 1], t[i] 14 | swapped = true 15 | end 16 | end 17 | if not swapped then 18 | break 19 | end 20 | swapped = false 21 | end_ = end_ - 1 22 | for i = end_, start, -1 do 23 | if t[i] < t[i - 1] then 24 | t[i], t[i - 1] = t[i - 1], t[i] 25 | swapped = true 26 | end 27 | end 28 | start = start + 1 29 | end 30 | return t 31 | end 32 | 33 | return cocktailSort -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailSort.py: -------------------------------------------------------------------------------- 1 | # cocktail sort function 2 | def cocktailSort(A): 3 | up = range(len(A)-1) 4 | while True: 5 | for indices in (up, reversed(up)): 6 | 7 | # reseting the swapped flag 8 | swapped = False 9 | 10 | # looping through left to right 11 | for i in indices: 12 | if A[i] > A[i+1]: 13 | A[i], A[i+1] = A[i+1], A[i] 14 | swapped = True 15 | 16 | # if noting is swapped means, array is sorted 17 | if not swapped: 18 | return 19 | 20 | # initializing the array 21 | array = [25,1,-2,70,100,-10,40,2,0,5] 22 | print("Array before sorting: ",array) 23 | 24 | cocktailSort(array) 25 | print("Array after sorting: ",array) -------------------------------------------------------------------------------- /sortingAlgo/cocktailSort/cocktailsort.java: -------------------------------------------------------------------------------- 1 | public class cocktail{ 2 | static int temp; 3 | static void Cocktail(int a[], int n){ 4 | boolean swap = true; 5 | int begin = 0,i; 6 | int end = n - 1; 7 | while (swap) { 8 | swap = false; 9 | for (i = begin; i < end; ++i){ 10 | if (a[i] > a[i + 1]){ 11 | temp = a[i]; 12 | a[i]=a[i+1]; 13 | a[i+1]=temp; 14 | swap = true; 15 | } 16 | } 17 | if (!swap) 18 | break; 19 | swap = false; 20 | for (i = end - 1; i >= begin; --i){ 21 | if (a[i] > a[i + 1]){ 22 | temp = a[i]; 23 | a[i]=a[i+1]; 24 | a[i+1]=temp; 25 | swap = true; 26 | } 27 | } 28 | ++begin; 29 | } 30 | } 31 | public static void main(String[] args) { 32 | int my_arr[] = {34, 78, 90, 32, 67, 12, 1, 0, 95}; 33 | Cocktail(my_arr, my_arr.length); 34 | System.out.println("The sorted array is "); 35 | for (int i = 0; i < my_arr.length; i++) 36 | System.out.print(my_arr[i]+" "); 37 | System.out.println(); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /sortingAlgo/combSort/combSort.c: -------------------------------------------------------------------------------- 1 | // C implementation of Comb Sort 2 | #include 3 | #include 4 | #include 5 | 6 | // To find gap between elements 7 | int getNextGap(int gap) 8 | { 9 | // Shrink gap by Shrink factor 10 | gap = (gap * 10) / 13; 11 | 12 | if (gap < 1) 13 | return 1; 14 | return gap; 15 | } 16 | 17 | // Function to sort a[0..n-1] using Comb Sort 18 | void combSort(int a[], int n) 19 | { 20 | // Initialize gap 21 | int gap = n; 22 | 23 | // Initialize swapped as true to make sure that 24 | // loop runs 25 | bool swapped = true; 26 | 27 | // Keep running while gap is more than 1 and last 28 | // iteration caused a swap 29 | while (gap != 1 || swapped == true) 30 | { 31 | // Find next gap 32 | gap = getNextGap(gap); 33 | 34 | // Initialize swapped as false so that we can 35 | // check if swap happened or not 36 | swapped = false; 37 | 38 | // Compare all elements with current gap 39 | for (int i = 0; i < n - gap; i++) 40 | { 41 | if (a[i] > a[i + gap]) 42 | { 43 | int temp = a[i]; 44 | a[i] = a[i + gap]; 45 | a[i + gap] = temp; 46 | swapped = true; 47 | } 48 | } 49 | } 50 | } 51 | 52 | // Driver program 53 | int main() 54 | { 55 | int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 56 | int n = sizeof(a) / sizeof(a[0]); 57 | 58 | combSort(a, n); 59 | 60 | printf("Sorted array: \n"); 61 | for (int i = 0; i < n; i++) 62 | printf("%d ", a[i]); 63 | 64 | return 0; 65 | } -------------------------------------------------------------------------------- /sortingAlgo/combSort/combSort.cpp: -------------------------------------------------------------------------------- 1 | // C++ implementation of Comb Sort 2 | #include 3 | using namespace std; 4 | 5 | // To find gap between elements 6 | int getNextGap(int gap) 7 | { 8 | // Shrink gap by Shrink factor 9 | gap = (gap * 10) / 13; 10 | 11 | if (gap < 1) 12 | return 1; 13 | return gap; 14 | } 15 | 16 | // Function to sort a[0..n-1] using Comb Sort 17 | void combSort(int a[], int n) 18 | { 19 | // Initialize gap 20 | int gap = n; 21 | 22 | // Initialize swapped as true to make sure that 23 | // loop runs 24 | bool swapped = true; 25 | 26 | // Keep running while gap is more than 1 and last 27 | // iteration caused a swap 28 | while (gap != 1 || swapped == true) 29 | { 30 | // Find next gap 31 | gap = getNextGap(gap); 32 | 33 | // Initialize swapped as false so that we can 34 | // check if swap happened or not 35 | swapped = false; 36 | 37 | // Compare all elements with current gap 38 | for (int i = 0; i < n - gap; i++) 39 | { 40 | if (a[i] > a[i + gap]) 41 | { 42 | swap(a[i], a[i + gap]); 43 | swapped = true; 44 | } 45 | } 46 | } 47 | } 48 | 49 | // Driver program 50 | int main() 51 | { 52 | int a[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 53 | int n = sizeof(a) / sizeof(a[0]); 54 | 55 | combSort(a, n); 56 | 57 | printf("Sorted array: \n"); 58 | for (int i = 0; i < n; i++) 59 | printf("%d ", a[i]); 60 | 61 | return 0; 62 | } -------------------------------------------------------------------------------- /sortingAlgo/combSort/combSort.cs: -------------------------------------------------------------------------------- 1 | // C# program for implementation of Comb Sort 2 | using System; 3 | 4 | class GFG 5 | { 6 | // To find gap between elements 7 | static int getNextGap(int gap) 8 | { 9 | // Shrink gap by Shrink factor 10 | gap = (gap*10)/13; 11 | if (gap < 1) 12 | return 1; 13 | return gap; 14 | } 15 | 16 | // Function to sort arr[] using Comb Sort 17 | static void sort(int []arr) 18 | { 19 | int n = arr.Length; 20 | 21 | // initialize gap 22 | int gap = n; 23 | 24 | // Initialize swapped as true to 25 | // make sure that loop runs 26 | bool swapped = true; 27 | 28 | // Keep running while gap is more than 29 | // 1 and last iteration caused a swap 30 | while (gap != 1 || swapped == true) 31 | { 32 | // Find next gap 33 | gap = getNextGap(gap); 34 | 35 | // Initialize swapped as false so that we can 36 | // check if swap happened or not 37 | swapped = false; 38 | 39 | // Compare all elements with current gap 40 | for (int i=0; i arr[i+gap]) 43 | { 44 | // Swap arr[i] and arr[i+gap] 45 | int temp = arr[i]; 46 | arr[i] = arr[i+gap]; 47 | arr[i+gap] = temp; 48 | 49 | // Set swapped 50 | swapped = true; 51 | } 52 | } 53 | } 54 | } 55 | 56 | // Driver method 57 | public static void Main() 58 | { 59 | int []arr = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 60 | sort(arr); 61 | 62 | Console.WriteLine("sorted array"); 63 | for (int i=0; i arr[i+gap]) 41 | { 42 | // Swap arr[i] and arr[i+gap] 43 | int temp = arr[i]; 44 | arr[i] = arr[i+gap]; 45 | arr[i+gap] = temp; 46 | 47 | // Set swapped 48 | swapped = true; 49 | } 50 | } 51 | } 52 | } 53 | 54 | // Driver method 55 | public static void main(String args[]) 56 | { 57 | CombSort ob = new CombSort(); 58 | int arr[] = {8, 4, 1, 56, 3, -44, 23, -6, 28, 0}; 59 | ob.sort(arr); 60 | 61 | System.out.println("sorted array"); 62 | for (int i=0; i 1 or swapped do 10 | gap = math.floor(gap / shrink) 11 | if gap < 1 then 12 | gap = 1 13 | end 14 | swapped = false 15 | for i = 1, n - gap do 16 | if t[i] > t[i + gap] then 17 | t[i], t[i + gap] = t[i + gap], t[i] 18 | swapped = true 19 | end 20 | end 21 | end 22 | return t 23 | end 24 | 25 | return combSort -------------------------------------------------------------------------------- /sortingAlgo/combSort/combSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of CombSort 2 | 3 | # To find next gap from current 4 | def getNextGap(gap): 5 | 6 | # Shrink gap by Shrink factor 7 | gap = (gap * 10)/13 8 | if gap < 1: 9 | return 1 10 | return gap 11 | 12 | # Function to sort arr[] using Comb Sort 13 | def combSort(arr): 14 | n = len(arr) 15 | 16 | # Initialize gap 17 | gap = n 18 | 19 | # Initialize swapped as true to make sure that 20 | # loop runs 21 | swapped = True 22 | 23 | # Keep running while gap is more than 1 and last 24 | # iteration caused a swap 25 | while gap !=1 or swapped == 1: 26 | 27 | # Find next gap 28 | gap = getNextGap(gap) 29 | 30 | # Initialize swapped as false so that we can 31 | # check if swap happened or not 32 | swapped = False 33 | 34 | # Compare all elements with current gap 35 | for i in range(0, n-gap): 36 | if arr[i] > arr[i + gap]: 37 | arr[i], arr[i + gap]=arr[i + gap], arr[i] 38 | swapped = True 39 | 40 | 41 | # Driver code to test above 42 | arr = [ 8, 4, 1, 3, -44, 23, -6, 28, 0] 43 | combSort(arr) 44 | 45 | print ("Sorted array:") 46 | for i in range(len(arr)): 47 | print (arr[i]), 48 | 49 | 50 | -------------------------------------------------------------------------------- /sortingAlgo/countingSort/countingSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() { 4 | int arrayLength; 5 | printf("How many numbers do you want to sort? "); 6 | scanf("%d",&arrayLength); 7 | int array[arrayLength]; 8 | int sortedArray[arrayLength]; 9 | int largest = 0; 10 | for (int i = 0; i < arrayLength; i++) { 11 | printf("%d. number:",i+1); 12 | int j; 13 | scanf("%d", &j); 14 | if (j > largest) { 15 | largest = j; 16 | } 17 | array[i] = j; 18 | } 19 | int count[largest+1]; 20 | for(int i = 0; i < largest+1; i++) { 21 | count[i] = 0; 22 | } 23 | for(int i = 0; i < arrayLength; i++) { 24 | count[array[i]]++; 25 | } 26 | for(int i = 1; i < largest+1; i++) { 27 | count[i] += count[i-1]; 28 | } 29 | for(int i = 0; i < arrayLength; i++) { 30 | sortedArray[count[array[i]]-1] = array[i]; 31 | count[array[i]] -= 1; 32 | } 33 | printf("\nSorted array: "); 34 | for(int i = 0; i < arrayLength; i++) { 35 | printf("%d ",sortedArray[i]); 36 | } 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /sortingAlgo/countingSort/countingSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define ll long long 8 | 9 | vector counting_sort(vector v, function key = [](ll x){return x;},ll k=-1) 10 | { 11 | vector w; 12 | w.reserve(v.size()); 13 | 14 | if(k==-1){ 15 | for(auto i : v) 16 | if(k> table(k+10); //vector 20 | 21 | for(auto i : v) 22 | table[key(i)].push_back(i); 23 | 24 | for(ll i=0; i<=k+5; i++) 25 | for(auto j : table[i]) 26 | w.push_back(j); 27 | 28 | return w; 29 | } 30 | 31 | int main() 32 | { 33 | vector v = {10, 9, 4, 5, 7}; 34 | 35 | for(auto i : v) 36 | cout< key; 40 | key = [](ll x) {return 11-x;}; 41 | 42 | v=counting_sort(v, key); 43 | 44 | cout<<"\n Sorted:\n"; 45 | for(auto i : v) 46 | cout< counting_sort(vector v, ll k) 55 | { 56 | vector w; 57 | w.reserve(v.size()); 58 | 59 | if(k==-1){ 60 | for(auto i : v) 61 | if(k table(k+10, 0); 65 | 66 | for(auto i : v) 67 | table[i]++; 68 | 69 | for(ll i=0; i<=k+5; i++) 70 | if(table[i]) 71 | while(table[i]--) 72 | w.push_back(i); 73 | 74 | return w; 75 | } 76 | */ -------------------------------------------------------------------------------- /sortingAlgo/countingSort/countingSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using counting sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function countingSort(t) 5 | local n = #t 6 | local counts = {} 7 | for i = 1, n do 8 | counts[t[i]] = (counts[t[i]] or 0) + 1 9 | end 10 | local k = 1 11 | for i = 1, n do 12 | if counts[i] then 13 | for j = 1, counts[i] do 14 | t[k] = i 15 | k = k + 1 16 | end 17 | end 18 | end 19 | return t 20 | end 21 | 22 | return countingSort -------------------------------------------------------------------------------- /sortingAlgo/countingSort/countingSort.py: -------------------------------------------------------------------------------- 1 | '''COUNTINGSORT 2 | Counting sort is a sorting technique based on keys between a specific range. 3 | It works by counting the number of objects having distinct key values. 4 | Then doing some arithmetic to calculate the position of each object in the 5 | output sequence.''' 6 | 7 | 8 | def countSort(arr): 9 | output = [0 for i in range(256)] 10 | count = [0 for i in range(256)] # Create a count array initialized with 0 11 | ans = ["" for _ in arr] # as strings are immutable 12 | 13 | for i in arr: 14 | count[ord(i)] += 1 # position of character in the output array 15 | 16 | 17 | for i in range(256): 18 | count[i] += count[i-1] # output character array 19 | 20 | 21 | for i in range(len(arr)): 22 | output[count[ord(arr[i])]-1] = arr[i] 23 | count[ord(arr[i])] -= 1 # array of sorted charcters 24 | 25 | 26 | for i in range(len(arr)): 27 | ans[i] = output[i] 28 | return ans 29 | 30 | 31 | 32 | #TEST 33 | arr = "Algorithms" 34 | ans = countSort(arr) 35 | print ("Sorted character array is "+str("".join(ans))) 36 | 37 | 38 | -------------------------------------------------------------------------------- /sortingAlgo/cycleSort/cycleSort.c: -------------------------------------------------------------------------------- 1 | //cycle sort - Sorts an array in minimum swaps 2 | 3 | #include 4 | 5 | void cycleSort(int *arr,int n) 6 | { 7 | for(int i=0;i 4 | using namespace std; 5 | 6 | void cycleSort(int *arr,int n) 7 | { 8 | for(int i=0;i= 0; i--) 32 | heapify(arr, i); 33 | ``` 34 | 35 | ## Complexity 36 | 37 | - Worst case time complexity: `O(n log n)` 38 | - Average case time complexity: `O(n log n)` 39 | - Best case time complexity: `O(n log n)` 40 | - Space complexity: `O(1)` 41 | 42 | ## Applications of Heap Sort 43 | * K sorted array 44 | * K largest or smallest elements in an array 45 | 46 | ### Instruction for Running code: 47 | - C 48 | ``` 49 | gcc heapSort.c 50 | ./a.out 51 | ``` 52 | - Cpp 53 | 54 | ```` 55 | g++ heapSort.cpp 56 | ./a.out 57 | ```` 58 | - Java 59 | 60 | ``` 61 | javac heapSort.java 62 | java heapSort.class 63 | ``` 64 | - Python 65 | ``` 66 | python3 heapSort.py 67 | ``` 68 | -------------------------------------------------------------------------------- /sortingAlgo/heapSort/heapSort.cpp: -------------------------------------------------------------------------------- 1 | // Heapsort and Min heap in C++ 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define ll long long 8 | 9 | void heapify(int i, vector &v) 10 | { 11 | if(v.empty() || 2*i+1>=v.size() || i<0) 12 | return; 13 | 14 | // int k=v[2*i+1]v[k+1]); 18 | 19 | if(v[i]>v[k]){ 20 | swap(v[i], v[k]); 21 | heapify(k, v); 22 | } 23 | } 24 | 25 | void build_heap(vector &v) 26 | { 27 | if(v.empty()) 28 | return; 29 | int i=(v.size()+1)/2; 30 | while(i--) 31 | heapify(i, v); 32 | } 33 | 34 | void insert(ll n, vector &v) 35 | { 36 | if(v.empty()) 37 | return; 38 | 39 | v.push_back(n); 40 | int i=v.size()-1; 41 | 42 | while(i && v[(i-1)/2]>v[i]) 43 | { 44 | swap(v[i], v[(i-1)/2]); 45 | i=(i-1)/2; 46 | } 47 | } 48 | 49 | ll extract_min(vector &v) 50 | { 51 | if(v.empty()) 52 | return -1; 53 | 54 | ll min=v[0]; 55 | v[0]=v.back(); 56 | v.pop_back(); 57 | heapify(0, v); 58 | 59 | return min; 60 | } 61 | 62 | ll find_min(const vector v){ 63 | return v.empty()?-1:v[0]; 64 | } 65 | 66 | vector heap_sort(vector v) 67 | { 68 | vector w; 69 | w.reserve(v.size()); 70 | 71 | build_heap(v); 72 | while(!v.empty()) 73 | w.push_back(extract_min(v)); 74 | 75 | return w; 76 | } 77 | 78 | int main() 79 | { 80 | //driver code 81 | 82 | vector v = {12, 11, 13, 5, 6, 7}; 83 | 84 | for(auto i : v) 85 | cout< t[largest] then 8 | largest = l 9 | end 10 | if r <= n and t[r] > t[largest] then 11 | largest = r 12 | end 13 | if largest ~= i then 14 | t[i], t[largest] = t[largest], t[i] 15 | heapify(t, n, largest) 16 | end 17 | end 18 | for i = math.floor(n / 2), 1, -1 do 19 | heapify(t, n, i) 20 | end 21 | for i = n, 2, -1 do 22 | t[1], t[i] = t[i], t[1] 23 | heapify(t, i - 1, 1) 24 | end 25 | end 26 | 27 | local t = { 3, 2, 1, 4, 5, 6, 7, 8, 9, 10 } 28 | heapSort(t) 29 | print(table.concat(t, ", ")) -------------------------------------------------------------------------------- /sortingAlgo/heapSort/heapSort.py: -------------------------------------------------------------------------------- 1 | #TC 2 | arr = [ 12, 11, 13, 5, 6, 7] 3 | 4 | def heapify(node, heap): 5 | if len(heap)==0 or 2*node+1>=len(heap) or node<0: 6 | return 7 | # next = 2*node+1 if heap[2*node+1]heap[2*node+2]) 10 | except IndexError: 11 | next = 2*node+1 12 | if heap[node]>heap[next]: 13 | heap[node], heap[next] = heap[next], heap[node] 14 | heapify(next, heap) 15 | 16 | def extractMin(heap): 17 | if len(heap)==0: 18 | return None 19 | min = heap[0] 20 | heap[0] = heap[-1] 21 | heap.pop() 22 | heapify(0, heap) 23 | return min 24 | 25 | def insert(ele, heap): 26 | heap.append(ele) 27 | point = len(heap)-1 28 | while heap[(point-1)//2]>heap[point] and point>=0: 29 | heap[(point-1)//2], heap[point] = heap[point], heap[(point-1)//2] 30 | point = (point-1)//2 31 | 32 | def buildHeap(heap): 33 | for node in range((len(heap)+1)//2, -1, -1): 34 | heapify(node, heap) 35 | 36 | def heapSort(heap): 37 | sorted=[] 38 | buildHeap(heap) 39 | while len(heap): 40 | sorted.append(extractMin(heap)) 41 | 42 | return sorted 43 | 44 | 45 | print(heapSort(arr)) 46 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/InsertionSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int n, array[1000], c, d, t; 6 | 7 | printf("Enter number of elements\n"); 8 | scanf("%d", &n); 9 | 10 | printf("Enter %d integers\n", n); 11 | 12 | for (c = 0; c < n; c++) 13 | scanf("%d", &array[c]); 14 | 15 | for (c = 1; c <= n - 1; c++) 16 | { 17 | d = c; 18 | 19 | while (d > 0 && array[d - 1] > array[d]) 20 | { 21 | t = array[d]; 22 | array[d] = array[d - 1]; 23 | array[d - 1] = t; 24 | d--; 25 | } 26 | } 27 | printf("Sorted list in ascending order:\n"); 28 | for (c = 0; c < n; c++) 29 | { 30 | printf("%d\n", array[c]); 31 | } 32 | return 0; 33 | } 34 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/InsertionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n, array[1000], c, d, t; 8 | 9 | printf("Enter number of elements\n"); 10 | scanf("%d", &n); 11 | 12 | printf("Enter %d integers\n", n); 13 | 14 | for (c = 0; c < n; c++) 15 | scanf("%d", &array[c]); 16 | 17 | for (c = 1; c <= n - 1; c++) 18 | { 19 | d = c; 20 | 21 | while (d > 0 && array[d - 1] > array[d]) 22 | { 23 | t = array[d]; 24 | array[d] = array[d - 1]; 25 | array[d - 1] = t; 26 | d--; 27 | } 28 | } 29 | printf("Sorted list in ascending order:\n"); 30 | for (c = 0; c < n; c++) 31 | { 32 | cout << array[c] << endl; 33 | } 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/Readme.md: -------------------------------------------------------------------------------- 1 |  2 | # Insertion Sort 3 | 4 | - Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each iteration. 5 | - Time Complexity: 6 | - Worst Case Complexity:O(n2) 7 | - Best Case Complexity:O(1) 8 | - Average Case Complexity:O(n2) 9 | - Worst Case Space Complexity:O(1) 10 | 11 | ### Logic 12 | 13 | 1. The first element in the array is assumed to be sorted. Take the second element and store it separately in `key`.Compare `key` with the first element. If the first element is greater than `key`, then key is placed in front of the first element.. 14 | 2. Now, the first two elements are sorted. Take the third element and compare it with the elements on the left of it. Placed it just behind the element smaller than it. If there is no element smaller than it, then place it at the beginning of the array. 15 | 3. Similarly, place every unsorted element at its correct position. 16 | ### Pseudo Code: 17 | 18 | for j <- 2 to length [_A_] 19 | 20 | do key <- A [_j_] 21 | 22 | Insert A [j] into the sorted sequence A[1..j-1] 23 | 24 | i<-j- 1 25 | 26 | while i >0 and A[i] >key 27 | 28 | do A[i+1]<-A[i] 29 | 30 | i <-i-1 31 | 32 | A[i + 1] <-key 33 | 34 | ### Instruction for Running code: 35 | 36 | 37 | - Cpp 38 | ``` 39 | g++ InsertionSort.cpp 40 | ./a.out 41 | ``` 42 | - Python 43 | ``` 44 | python3 InsertionSort.py 45 | ``` 46 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/insertionSort.cc: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void insertionsort(int a[], int n) { 6 | for(int i = 1; i < n; ++i) { 7 | int j = i-1; 8 | int key = a[i]; 9 | while(j > -1 && a[j] > key) { 10 | swap(a[j+1], a[j]); 11 | --j; 12 | } 13 | a[j+1] = key; 14 | } 15 | } 16 | 17 | void insertionsort_rec(int a[], int n) { 18 | if(n < 2) return; 19 | insertionsort_rec(a, n-1); 20 | 21 | int key = a[n-1]; 22 | int j = n-2; 23 | 24 | while(j > -1 && a[j] > key) { 25 | swap(a[j+1], a[j]); 26 | --j; 27 | } 28 | 29 | a[j+1] = key; 30 | 31 | } 32 | 33 | int main() { 34 | int arr[10] = {3, 450, 12, 4, -1, 0, 24, 95, 123, 0}; 35 | for(int i = 0; i < 10; ++i) 36 | cout << *(arr+i) << ' '; 37 | cout << endl; 38 | insertionsort_rec(arr, 10); 39 | for(int i = 0; i < 10; ++i) 40 | cout << *(arr+i) << ' '; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/insertionSort.java: -------------------------------------------------------------------------------- 1 | class insertionSort { 2 | public static void insertionSort(int array[]) { 3 | int n = array.length; 4 | for (int j = 1; j < n; j++) { 5 | int key = array[j]; 6 | int i = j-1; 7 | while ( (i > -1) && ( array [i] > key ) ) { 8 | array [i+1] = array [i]; 9 | i--; 10 | } 11 | array[i+1] = key; 12 | } 13 | } 14 | 15 | public static void main(String a[]){ 16 | int[] arr1 = {9,14,3,2,43,11,58,22}; 17 | System.out.println("Before Insertion Sort"); 18 | for(int i:arr1){ 19 | System.out.print(i+" "); 20 | } 21 | System.out.println(); 22 | 23 | insertionSort(arr1);//sorting array using insertion sort 24 | 25 | System.out.println("After Insertion Sort"); 26 | for(int i:arr1){ 27 | System.out.print(i+" "); 28 | } 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/insertionSort.js: -------------------------------------------------------------------------------- 1 | function insertionSort(inputArr) { 2 | 3 | let n = inputArr.length; 4 | 5 | for (let i = 1; i < n; i++) { 6 | // Choosing the first element in the unsorted subarray 7 | let current = inputArr[i]; 8 | 9 | // The last element of the sorted subarray 10 | let j = i - 1; 11 | 12 | while ((j > -1) && (current < inputArr[j])) { 13 | inputArr[j + 1] = inputArr[j]; 14 | j--; 15 | } 16 | 17 | inputArr[j + 1] = current; 18 | } 19 | 20 | return inputArr; 21 | } 22 | 23 | let inputArr = [5, 2, 4, 6, 1, 3]; 24 | 25 | insertionSort(inputArr); 26 | 27 | console.log(inputArr); 28 | -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/insertionSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the insertion sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function insertionSort(t) 5 | local n = #t 6 | for i = 2, n do 7 | local item = t[i] 8 | local j = i - 1 9 | while j > 0 and t[j] > item do 10 | t[j + 1] = t[j] 11 | j = j - 1 12 | end 13 | t[j + 1] = item 14 | end 15 | return t 16 | end 17 | 18 | return insertionSort -------------------------------------------------------------------------------- /sortingAlgo/insertionSort/insertionSort.py: -------------------------------------------------------------------------------- 1 | # Testcase 2 | arr = [1, 63, 103, 3, 8, 74, 76, 37, 71, 66] 3 | l = len(arr) 4 | 5 | def insertionSort(arr): 6 | for i in range(1,l): 7 | if arr[i] < arr[i - 1]: 8 | for j in range(i): 9 | if arr[i] < arr[j]: 10 | x = arr[i] 11 | del arr[i] 12 | arr.insert(j, x) 13 | return arr 14 | 15 | print(insertionSort(arr)) 16 | 17 | -------------------------------------------------------------------------------- /sortingAlgo/mergeSort/mergeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void merge(int A[], int i1, int j1, int i2, int j2){ 4 | int temp[j2 -i1 + 5]; 5 | int i = i1, j = i2, k = 0; 6 | 7 | while(i<=j1 && j<=j2) 8 | { 9 | if(A[i] arr2[0]: 29 | arr.append(arr2[0]) 30 | del arr2[0] 31 | l2 -= 1 32 | elif arr1[0] < arr2[0]: 33 | arr.append(arr1[0]) 34 | del arr1[0] 35 | l1 -= 1 36 | else: 37 | arr.append(arr1[0]) 38 | arr.append(arr2[0]) 39 | del arr2[0] 40 | del arr1[0] 41 | l1 -= 1 42 | l2 -= 1 43 | 44 | if l1 == 0: 45 | arr.extend(arr2) 46 | else: 47 | arr.extend(arr1) 48 | 49 | return arr 50 | 51 | print(mergeSort(arr)) 52 | -------------------------------------------------------------------------------- /sortingAlgo/mergeSort/mergeSort.swift: -------------------------------------------------------------------------------- 1 | // a function that merges two arrys 2 | func merge(_ array_1: inout [Int], _ low: Int, _ mid: Int, _ high: Int) { 3 | var i = low 4 | var j = mid + 1 5 | var k = 0 6 | 7 | var array_2: [Int] = [Int](repeating: 0, count: high - low + 1) 8 | 9 | while i <= mid && j <= high { 10 | if array_1[i] <= array_1[j] { 11 | array_2[k] = array_1[i] 12 | k += 1 13 | i += 1 14 | } 15 | else { 16 | array_2[k] = array_1[j] 17 | k += 1 18 | j += 1 19 | } 20 | } 21 | 22 | while i <= mid { 23 | array_2[k] = array_1[i] 24 | k += 1 25 | i += 1 26 | } 27 | 28 | while j <= high { 29 | array_2[k] = array_1[j] 30 | k += 1 31 | j += 1 32 | } 33 | 34 | for i in low...high { 35 | array_1[i] = array_2[i - low] 36 | } 37 | } 38 | 39 | // the recursive sorting algorithm that divides the array, sorts the two halves and merges them 40 | func sort(_ array: inout [Int], _ low: Int, _ high: Int) { 41 | if low < high { 42 | let mid = (low + high) / 2 43 | sort(&array, low, mid) 44 | sort(&array, mid + 1, high) 45 | merge(&array, low, mid, high) 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/Readme.md: -------------------------------------------------------------------------------- 1 |  2 | # Pigeonhole Sort 3 | 4 | -Pigeonhole Sort is a sorting algorithm that is suitable for sorting lists of elements where the number of elements (n) and the number of possible key values (N) are approximately the same. It requires O(n + Range) time where n is number of elements in input array and ‘Range’ is number of possible values in array. 5 | - Worst-case Complexity:O(N+n) 6 | - Worst-case Space Complexity:O(N+n) 7 | 8 | ### Logic 9 | 10 | 1.Find minimum and maximum values in array. Let the minimum and maximum values be ‘min’ and ‘max’ respectively. Also find range as **max-min+1**. 11 | 2. Set up an array of initially empty “pigeonholes” the same size as of the range calculated above. 12 | 3. Visit each element of the array and then put each element in its pigeonhole. An element **arr[i]** is put in hole at index **arr[i] – min**. 13 | 4. Start the loop all over the pigeonhole array in order and put the elements from non- empty holes back into the original array. 14 | ### Pseudo Code: 15 | 16 | 17 | function pigeonhole_sort(a) 18 | 19 | let my_min ← min(a) 20 | let my_max ← max(a) 21 | let size ← my_max - my_min + 1 22 | let holes ← [0] * size 23 | for x in a 24 | if x is not integer 25 | return -1 26 | holes[x - my_min] += 1 27 | let i ← 0 28 | for count in (0,size) 29 | while holes[count] > 0: 30 | holes[count] -= 1 31 | a[i] ← count + my_min 32 | i += 1 33 | ### Instruction for Running code: 34 | 35 | 36 | - Cpp 37 | ``` 38 | g++ pigeonholeSort.cpp 39 | ./a.out 40 | ``` 41 | - Python 42 | ``` 43 | python3 piegeonholeSort.py 44 | ``` 45 | -javascript 46 | ``` 47 | javascript pigeonholeSort.js 48 | -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/pigeonholeSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void pigeonhole_sort(int arr[], int n) { 5 | // Find the minimum and maximum elements in the array 6 | int minn = arr[0]; 7 | int maks = arr[0]; 8 | 9 | for (int i = 1; i < n; i++) { 10 | if (arr[i] < minn) { 11 | minn = arr[i]; 12 | } else if (arr[i] > maks) { 13 | maks = arr[i]; 14 | } 15 | } 16 | 17 | // Calculate the range of possible key values 18 | int range = maks - minn + 1; 19 | 20 | // Create an array of vectors to hold elements with the same key 21 | // The size of 'holes' array is equal to the range 22 | int *holes[range]; 23 | for (int i = 0; i < range; i++) { 24 | holes[i] = malloc(sizeof(int) * n); 25 | } 26 | 27 | // Initialize counts for each hole to zero 28 | int counts[range]; 29 | 30 | for (int i = 0; i < range; i++) { 31 | counts[i] = 0; 32 | } 33 | 34 | // Distribute elements into the holes based on their keys 35 | for (int i = 0; i < n; i++) { 36 | int key = arr[i] - minn; 37 | holes[key][counts[key]] = arr[i]; 38 | counts[key]++; 39 | } 40 | 41 | // Copy elements from holes back to the original array 42 | int j = 0; 43 | for (int i = 0; i < range; i++) { 44 | for (int k = 0; k < counts[i]; k++) { 45 | arr[j] = holes[i][k]; 46 | j++; 47 | } 48 | free(holes[i]); // Free the memory allocated for each hole 49 | } 50 | } 51 | 52 | int main() { 53 | int n; 54 | scanf("%d", &n); 55 | int *a = malloc(sizeof(int) * n); 56 | 57 | for (int i = 0; i < n; i++) { 58 | scanf("%d", &a[i]); 59 | } 60 | 61 | pigeonhole_sort(a, n); 62 | 63 | for (int i = 0; i < n; i++) { 64 | printf("%d ", a[i]); 65 | } 66 | printf("\n"); 67 | 68 | free(a); // Free the memory allocated for the array 'a' 69 | return 0; 70 | } 71 | 72 | 73 | /* here n is the number of elements in the array to be sorted and a[0...n-1] is the array. 74 | input example: 75 | 5 76 | 5 4 3 2 1 77 | Output: 78 | 1 2 3 4 5 79 | Length of the range of possible key values = N; number of elements in the array =n; 80 | Overall time complexity = O(n+N) ; Overall Space complexity = O(N) */ -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/pigeonholeSort.cpp: -------------------------------------------------------------------------------- 1 | // Pigeonhole Sort in C++ 2 | #include 3 | using namespace std; 4 | 5 | void pigeonhole_sort(int arr[], int n) 6 | { 7 | int minn = *min_element(arr, arr+ n) ; 8 | int maks = *max_element(arr, arr+ n) ; 9 | 10 | int range = maks - minn + 1; 11 | 12 | vector holes[range]; 13 | 14 | for (int i = 0; i < n; i++) 15 | holes[arr[i]-minn].push_back(arr[i]); 16 | 17 | int j = 0; 18 | for (int i = 0; i < range; i++) 19 | { 20 | for(int k = 0 ; k < holes[i].size() ; k++) 21 | { 22 | arr[j] = holes[i][k] ; 23 | j++ ; 24 | } 25 | } 26 | } 27 | 28 | int main() 29 | { 30 | int n ; cin >> n ; 31 | int a[n] ; 32 | for(int i = 0 ; i < n ; i ++) cin >> a[i] ; 33 | 34 | pigeonhole_sort(a , n) ; 35 | 36 | 37 | for(int i = 0 ; i < n ; i++) cout << a[i] << " " ; 38 | } 39 | 40 | /* here n is the number of elements in the array to be sorted and a[0...n-1] is the array. 41 | input example: 42 | 5 43 | 5 4 3 2 1 44 | Output: 45 | 1 2 3 4 5 46 | Length of the range of possible key values = N; number of elements in the array =n; 47 | Overall time complexity = O(n+N) ; Overall Space complexity = O(N) */ 48 | -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/pigeonholeSort.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class GFG 4 | { 5 | public static void pigeonhole_sort(int []arr, int n) 6 | { 7 | int min = arr[0]; 8 | int max = arr[0]; 9 | int range, i, j, index; 10 | 11 | for(int a = 0; a < n; a++) 12 | { 13 | if(arr[a] > max) 14 | max = arr[a]; 15 | if(arr[a] < min) 16 | min = arr[a]; 17 | } 18 | 19 | range = max - min + 1; 20 | int[] phole = new int[range]; 21 | 22 | for(i = 0; i < n; i++) 23 | phole[i] = 0; 24 | 25 | for(i = 0; i < n; i++) 26 | phole[arr[i] - min]++; 27 | 28 | 29 | index = 0; 30 | 31 | for(j = 0; j < range; j++) 32 | while(phole[j] --> 0) 33 | arr[index++] = j + min; 34 | 35 | } 36 | 37 | // Driver Code 38 | static void Main() 39 | { 40 | int[] arr = {8, 3, 2, 7, 41 | 4, 6, 8}; 42 | 43 | Console.Write("Sorted order is : "); 44 | 45 | pigeonhole_sort(arr,arr.Length); 46 | 47 | for(int i = 0 ; i < arr.Length ; i++) 48 | Console.Write(arr[i] + " "); 49 | } 50 | } -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/pigeonholeSort.java: -------------------------------------------------------------------------------- 1 | import java.lang.*; 2 | import java.util.*; 3 | 4 | public class MySort 5 | { 6 | public static void pigeonholeSort(int arr[], int n) 7 | { 8 | int min = arr[0]; 9 | int max = arr[0]; 10 | int range, i, j, index; 11 | 12 | for(int a=0; a max) 15 | max = arr[a]; 16 | if(arr[a] < min) 17 | min = arr[a]; 18 | } 19 | 20 | range = max - min + 1; 21 | int[] phole = new int[range]; 22 | Arrays.fill(phole, 0); 23 | 24 | for(i = 0; i0) 32 | arr[index++]=j+min; 33 | 34 | } 35 | 36 | public static void main(String[] args) 37 | { 38 | MySort sort = new MySort(); 39 | int[] arr = {8, 3, 2, 7, 4, 6, 8}; 40 | 41 | System.out.print("Sorted order is : "); 42 | 43 | sort.pigeonholeSort(arr,arr.length); 44 | 45 | for(int i=0 ; i max) max = input[i]; 12 | } 13 | 14 | let range = max - min + 1;// Find range 15 | var holes =[range]; 16 | 17 | for(var i = 0; i < n; i++) { 18 | holes[i] = 0; 19 | 20 | } 21 | 22 | // Traverse through input array and put every 23 | // element in its respective hole 24 | for(var i = 0; i < n; i++) 25 | holes[input[i] - min]++; 26 | 27 | // Traverse through all holes one by one. For 28 | // every hole, take its elements and put in 29 | // array. 30 | 31 | var i=0; // index in sorted array 32 | for(var j = 0; j < range; j++) { 33 | 34 | while(holes[j]>0){ 35 | 36 | holes[j] -= 1; 37 | input[i] = j+min; 38 | i += 1; 39 | } 40 | 41 | } 42 | } 43 | 44 | function display(){ 45 | let input=[1, 3, 2, 7, 46 | 4, 6, 11]; 47 | SortPigeonhole(input); 48 | console.log("Element after sort :") 49 | 50 | for(var i=0;i max then 13 | max = t[i] 14 | end 15 | end 16 | local holes = {} 17 | for i = 1, n do 18 | holes[i] = 0 19 | end 20 | for i = 1, n do 21 | holes[t[i] - min + 1] = holes[t[i] - min + 1] + 1 22 | end 23 | local k = 1 24 | for i = 1, n do 25 | while holes[i] > 0 do 26 | t[k] = i + min - 1 27 | k = k + 1 28 | holes[i] = holes[i] - 1 29 | end 30 | end 31 | return t 32 | end 33 | 34 | return pigeonholeSort -------------------------------------------------------------------------------- /sortingAlgo/pigeonholeSort/pigeonholeSort.py: -------------------------------------------------------------------------------- 1 | def pigeonholeSort(a): 2 | 3 | my_min = min(a) 4 | my_max = max(a) 5 | size = my_max - my_min + 1 6 | 7 | # our list of pigeonholes 8 | holes = [0] * size 9 | 10 | # Populate the pigeonholes. 11 | for x in a: 12 | assert type(x) is int, "Input Only Integers" 13 | holes[x - my_min] += 1 14 | 15 | # Put the elements back into the array in order. 16 | i = 0 17 | for count in range(size): 18 | while holes[count] > 0: 19 | holes[count] -= 1 20 | a[i] = count + my_min 21 | i += 1 22 | #Get The Size of The Array 23 | print("Enter the Size of the Array :") 24 | n=int(input()) 25 | a=[] 26 | #Get The Elements of The Array 27 | for i in range(0,n): 28 | ele=int(input()) 29 | a.append(ele) 30 | 31 | print("Pigeon Hole Sorted order is : ", end = ' ') 32 | 33 | pigeonholeSort(a) 34 | 35 | for i in range(0, len(a)): 36 | print(a[i], end = ' ') -------------------------------------------------------------------------------- /sortingAlgo/quickSort/QuickSort.java: -------------------------------------------------------------------------------- 1 | public class QuickSort { 2 | public static void main(String[] args) { 3 | int i; 4 | int[] arr={90,23,101,45,65,23,67,89,34,23}; //input array 5 | quickSort(arr, 0, 9); 6 | System.out.println("\n The sorted array is: \n"); 7 | for(i=0;i<10;i++) 8 | System.out.println(arr[i]); 9 | } 10 | public static int partition(int a[], int beg, int end) 11 | { 12 | 13 | int left, right, temp, loc, flag; 14 | loc = left = beg; 15 | right = end; 16 | flag = 0; 17 | while(flag != 1) 18 | { 19 | while((a[loc] <= a[right]) && (loc!=right)) 20 | right--; 21 | if(loc==right) 22 | flag =1; 23 | else if(a[loc]>a[right]) 24 | { 25 | temp = a[loc]; 26 | a[loc] = a[right]; 27 | a[right] = temp; 28 | loc = right; 29 | } 30 | if(flag!=1) 31 | { 32 | while((a[loc] >= a[left]) && (loc!=left)) 33 | left++; 34 | if(loc==left) 35 | flag =1; 36 | else if(a[loc] 2 | void swap(int array[] ,int index1, int index2); 3 | int partition(int array[], int low, int high); 4 | void quickSort(int array[], int low, int high); 5 | 6 | int main() { 7 | int array[9] = {2,9,3,8,6,5,4,7,10}; 8 | printf("Original array: "); 9 | for (int i = 0; i < 9; i++) { 10 | printf("%d ", array[i]); 11 | } 12 | 13 | quickSort(array, 0,9); 14 | 15 | printf("\nSorted array: "); 16 | for (int i = 0; i < 9; i++) { 17 | printf("%d ", array[i]); 18 | } 19 | 20 | return 0; 21 | } 22 | 23 | void swap(int array[], int index1, int index2) { 24 | int temp = array[index2]; 25 | array[index2] = array[index1]; 26 | array[index1] = temp; 27 | } 28 | 29 | 30 | 31 | 32 | int partition(int array[], int low, int high) { 33 | int pivot = array[low]; 34 | int i = 0; 35 | int j = high; 36 | 37 | while(i < j) { 38 | do { 39 | i++; 40 | } while (array[i] <= pivot); 41 | 42 | do { 43 | j--; 44 | } while (array[j] > pivot); 45 | if (i < j) { 46 | swap(array, i, j); 47 | } 48 | } 49 | swap(array, low, j); 50 | return j; 51 | } 52 | 53 | 54 | void quickSort(int array[], int low, int high) { 55 | if (low < high) { 56 | int j = partition(array, low, high); 57 | quickSort(array, low, j); 58 | quickSort(array, j+1, high); 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /sortingAlgo/quickSort/quickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | void quick_sort(int[],int,int); 6 | int partition(int[],int,int); 7 | 8 | int main() 9 | { 10 | int a[] ={90,23,101,45,65,23,67,89,34,23} ; // sample test case to demo the quicksort function 11 | int n = 10; 12 | quick_sort(a,0,n-1); 13 | cout<<"\nArray after sorting:"; 14 | 15 | for(int i=0;i 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | #define ll long long 8 | 9 | ll power(ll x, ll y)//fast integer exponentiation 10 | { 11 | ll ans=1; 12 | while(y) 13 | { 14 | if(y&1) 15 | ans*=x; 16 | y/=2; 17 | x*=x; 18 | } 19 | 20 | return ans; 21 | } 22 | 23 | vector counting_sort(vector v, function key = [](ll x){return x;}, ll k=-1) 24 | { 25 | vector w; 26 | w.reserve(v.size()); 27 | 28 | if(k==-1){ 29 | for(auto i : v) 30 | if(k> table(k+10); //vector 34 | 35 | for(auto i : v) 36 | table[key(i)].push_back(i); 37 | 38 | for(ll i=0; i<=k+5; i++) 39 | for(auto j : table[i]) 40 | w.push_back(j); 41 | 42 | return w; 43 | } 44 | 45 | vector radix_sort(vector v, ll k=-1) 46 | { 47 | if(k==-1){ 48 | for(auto i : v) 49 | if(k key; 61 | key = [i,b](ll x){return ((x/power(b,i))%b);}; 62 | v=counting_sort(v, key, k); 63 | } 64 | 65 | return v; 66 | } 67 | 68 | int main() 69 | { 70 | vector v = {10, 9, 4, 5, 7}; 71 | 72 | for(auto i : v) 73 | cout<[] bucket = new ArrayList[RADIX]; 14 | // Do counting sort for every digit. Note that 15 | // instead of passing digit number, exp is passed. 16 | // exp is 10^i where i is current digit number 17 | for (int i = 0; i < bucket.length; i++) { 18 | bucket[i] = new ArrayList(); 19 | } 20 | boolean maxLength = false; int tmp = -1, placement = 1; 21 | while (!maxLength) { 22 | maxLength = true; 23 | for (Integer i : input) { 24 | tmp = i / placement; 25 | bucket[tmp % RADIX].add(i); 26 | if (maxLength && tmp > 0) { 27 | maxLength = false; 28 | } 29 | } 30 | 31 | int a = 0; 32 | for (int b = 0; b < RADIX; b++) { 33 | for (Integer i : bucket[b]) { 34 | input[a++] = i; 35 | } 36 | bucket[b].clear(); 37 | } 38 | placement *= RADIX; 39 | } 40 | return input; 41 | } 42 | } -------------------------------------------------------------------------------- /sortingAlgo/radixSort/radixSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the radix sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function radixSort(t) 5 | local n = #t 6 | local max = 0 7 | for i = 1, n do 8 | if t[i] > max then 9 | max = t[i] 10 | end 11 | end 12 | local exp = 1 13 | while max / exp > 0 do 14 | local counts = {} 15 | for i = 1, n do 16 | local digit = math.floor(t[i] / exp) % 10 17 | counts[digit] = (counts[digit] or 0) + 1 18 | end 19 | for i = 1, 9 do 20 | counts[i] = (counts[i] or 0) + (counts[i - 1] or 0) 21 | end 22 | local sorted = {} 23 | for i = n, 1, -1 do 24 | local digit = math.floor(t[i] / exp) % 10 25 | sorted[counts[digit]] = t[i] 26 | counts[digit] = counts[digit] - 1 27 | end 28 | for i = 1, n do 29 | t[i] = sorted[i] 30 | end 31 | exp = exp * 10 32 | end 33 | return t 34 | end 35 | 36 | return radixSort -------------------------------------------------------------------------------- /sortingAlgo/radixSort/radixSort.py: -------------------------------------------------------------------------------- 1 | #TC 2 | arr = [10, 7, 8, 1, 4, 2, 5] 3 | 4 | def countingSort(arr, k=-1, key=(lambda x:x)): 5 | if k==-1: 6 | k = max(arr) 7 | 8 | table = [[] for _ in range(k+3)] 9 | 10 | for n in arr: 11 | table[key(n)].append(n) 12 | 13 | arr = [] 14 | for i in table: 15 | arr.extend(i) 16 | return arr 17 | 18 | def radixSort(arr, k=-1): 19 | b = len(arr) # base for radix sort 20 | 21 | if k==-1: 22 | k = max(arr) 23 | 24 | #calculate number of digits in k when in base b 25 | d = 0 26 | copy = k 27 | while copy: 28 | d+=1 29 | copy/=b 30 | 31 | for pos in range(d): 32 | arr = countingSort(arr, k, lambda x : (x//(b**pos))%b ) 33 | 34 | return arr 35 | 36 | 37 | print(radixSort(arr)) -------------------------------------------------------------------------------- /sortingAlgo/selectionSort/selectionSort.cc: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | 6 | void selectionsort(int a[], int n) { 7 | for(int i = 0; i < n-1; ++i) { 8 | int min = i; 9 | for(int j = i+1; j < n; ++j) { 10 | if(a[j] < a[min]) 11 | min = j; 12 | } 13 | 14 | swap(a[min], a[i]); 15 | } 16 | } 17 | 18 | int min_i(int a[], int i, int j) { 19 | if(i == j) return i; 20 | 21 | int k = min_i(a, i+1, j); 22 | return (a[i] < a[k]) ? i : k; 23 | } 24 | 25 | void selectionsort_rec(int* a, int b, int e=0) { 26 | if(b == e) return; 27 | 28 | int key = min_i(a, e, b-1); 29 | if(key != e) 30 | swap(a[key], a[e]); 31 | 32 | selectionsort_rec(a, b, e+1); 33 | } 34 | 35 | int main() { 36 | int arr[] = {3,450,12,4,-1,0,24,95,123,0}; 37 | for(int i = 0; i < 10; ++i) { 38 | cout << *(arr+i) << ' '; 39 | } 40 | cout << endl; 41 | selectionsort_rec(arr, 10); 42 | for(int i = 0; i < 10; ++i) { 43 | cout << *(arr+i) << ' '; 44 | } 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /sortingAlgo/selectionSort/selectionSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the selection sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function selectionSort(t) 5 | local n = #t 6 | for i = 1, n - 1 do 7 | local min = i 8 | for j = i + 1, n do 9 | if t[j] < t[min] then 10 | min = j 11 | end 12 | end 13 | t[i], t[min] = t[min], t[i] 14 | end 15 | return t 16 | end 17 | 18 | return selectionSort -------------------------------------------------------------------------------- /sortingAlgo/selectionSort/selectionSort.md: -------------------------------------------------------------------------------- 1 | # Selection Sort 2 | Selection sort is an algorithm that separates an array into two subsections: a sorted section, and an unsorted section. The array is sorted by moving the lowest value element to the beginning of the unsorted section. It can also be adjusted to sort in reverse order. 3 | ``` 4 | selection sort(array) 5 | for i <- 0 to indexOfLastElement: 6 | k = i 7 | for j <- i + 1 to indexOfLastElement: 8 | if (array[j] < array[k]) 9 | k = j 10 | swap array[k] and array[i] 11 | ``` 12 | 13 | ## Time Complexities: 14 | - Worst Case/Average: O(n2) 15 | - Best Case: O(n) 16 | Selection sort is inefficient on large lists. 17 | 18 | ## Space Complexity: 19 | - O(1) 20 | Selection sort has a space complexity of O(1), making it efficient when memory is lacking. 21 | 22 | ## Instructions for running Code: 23 | - cpp 24 | ``` 25 | g++ selectionSort.cc 26 | ./a.out 27 | ``` 28 | - python 29 | ``` 30 | python3 selectionSort.py 31 | -------------------------------------------------------------------------------- /sortingAlgo/selectionSort/selectionSort.py: -------------------------------------------------------------------------------- 1 | # Testcase 2 | arr = [63, 1, 103, 3, 8, 74, 76, 37, 71, 66] 3 | l = len(arr) 4 | 5 | def selectionSort(arr): 6 | for i in range(l): 7 | idx = i 8 | iPlusOne = i + 1 9 | for j in range(iPlusOne, l): 10 | if arr[j] < arr[idx]: 11 | idx = j 12 | 13 | arr[i], arr[idx] = arr[idx], arr[i] 14 | return arr 15 | 16 | print(selectionSort(arr)) 17 | -------------------------------------------------------------------------------- /sortingAlgo/selectionSort/selectionsort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void main() 4 | { 5 | int n,c,d,position,swap; 6 | printf("Enter number of elements\n"); 7 | scanf("%d",&n); 8 | int array[n]; 9 | printf("Enter %d integers\n",n); 10 | for(c=0;carray[d]) 17 | position=d; 18 | } 19 | if(position !=c) { 20 | swap = array[c]; 21 | array[c] = array[position]; 22 | array[position] = swap; 23 | } 24 | } 25 | printf("Sorted list in ascending order:\n"); 26 | for(c = 0; c2) 20 | - #### Best Case Complexities: O(n\*log n) 21 | When the array is already sorted, the total number of comparisons for each interval (or increment) is equal to the size of the array. 22 | - #### Average Case Complexity: O(n\*log n) 23 | It occurs when the elements of the array are in jumbled order (neither ascending nor descending). 24 | 25 | ### Space Complexity: 26 | 27 | The space complexity for shell sort is **O(1)** 28 | 29 | ### Shell Sort Applications: 30 | 31 | Shell sort is used when 32 | 33 | 1. calling a stack is overhead. 34 | 2. recursion exceeds a limit. 35 | 3. Insertion sort does not perform well when the close elements are far apart. Shell sort helps in reducing the distance between the close elements. Thus, there will be less number of swappings to be performed. 36 | 37 | ### Instruction for Running code: 38 | 39 | - Python 40 | ``` 41 | python3 ShellSort.py 42 | ``` 43 | -------------------------------------------------------------------------------- /sortingAlgo/shellSort/ShellSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void shellsort(int arr[], int num) 4 | { 5 | // Rearrange elements at each n/2, n/4, n/8, ... intervals 6 | for (int i = num / 2; i > 0; i /= 2) 7 | { 8 | for (int j = i; j < num; j++) 9 | { 10 | for (int k = j - i; k >= 0; k -= i) 11 | { 12 | if (arr[k + i] >= arr[k]) 13 | break; 14 | //swap the elements if the element is larger than the next element 15 | else 16 | { 17 | int tmp = arr[k]; 18 | arr[k] = arr[k + i]; 19 | arr[k + i] = tmp; 20 | } 21 | } 22 | } 23 | } 24 | } 25 | 26 | /** 27 | * Driver code. 28 | */ 29 | int main() 30 | { 31 | int arr[] = {11, 24, 53, 46, 55, 60, 17, 58, 29, 10}; 32 | int size = sizeof(arr) / sizeof(arr[0]); 33 | 34 | shellsort(arr, size); 35 | 36 | for (int k = 0; k < size; k++) 37 | printf("%d ", arr[k]); 38 | printf("\n"); 39 | 40 | return 0; 41 | } 42 | 43 | /* 44 | TIme Complexity : O(nlog(n)) 45 | Space Complexity : O(1) 46 | */ -------------------------------------------------------------------------------- /sortingAlgo/shellSort/ShellSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | /** 6 | * This function implements the Shell Sorting Algorithm. 7 | * 8 | * @note Knuth sequence was used. 9 | * 10 | * @param v Vector to be sorted. 11 | */ 12 | void shellSort(std::vector &v) { 13 | int gap; 14 | // calculate the first gap, based on Knuth sequence 15 | for(gap = 1; gap < (v.end() - v.begin()); gap = 3 * gap + 1); 16 | while(gap > 0) { // change to while(gap) 17 | // descrease the gap 18 | gap = (gap - 1)/3; 19 | // pass by elements to swap then if necessary 20 | for(size_t i = 0; v.begin() + gap + i < v.end(); i++) { 21 | if(*(v.begin() + gap + i) < *(v.begin() + i)) { 22 | std::swap(*(v.begin() + gap + i), *(v.begin() + i)); 23 | // in case some element was sawpped, it will try swap the elements before, maintaining the gap 24 | for(int j = i - gap; j >= 0; j -= gap) { 25 | if(*(v.begin() + gap + j) < *(v.begin() + j)) { std::swap(*(v.begin() + gap + j), *(v.begin() + j)); } 26 | } 27 | } 28 | } 29 | 30 | } 31 | } 32 | 33 | /** 34 | * Simple print function. 35 | */ 36 | void printVec(std::vector v) { 37 | for(int i = 0; i < v.size(); i++) std::cout << v[i] << " "; 38 | std::cout << std::endl; 39 | } 40 | 41 | /** 42 | * Driver code. 43 | */ 44 | int main() { 45 | std::vector v = {23, -10, 20, -11, 12, -6, 7, 299, 9, -1, 37, 51, 0}; 46 | shellSort(v); 47 | std::cout << "Sorted: "; 48 | printVec(v); 49 | 50 | return 0; 51 | } -------------------------------------------------------------------------------- /sortingAlgo/shellSort/ShellSort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | public class ShellSort { 4 | public static int[] shellSort(int arr[]) { 5 | int n = arr.length; 6 | // Start with a big gap, then reduce the gap 7 | for (int gap = n/2; gap > 0; gap /= 2) { 8 | // add a[i] to the elements that have been gap 9 | // sorted save a[i] in temp and make a hole at 10 | // position i 11 | for (int i = gap; i < n; i += 1) { 12 | int temp = arr[i]; 13 | // shift earlier gap-sorted elements up until 14 | // the correct location for a[i] is found 15 | int j; 16 | for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) { 17 | arr[j] = arr[j - gap]; 18 | } 19 | // put temp (the original a[i]) in its correct 20 | // location 21 | arr[j] = temp; 22 | } 23 | } 24 | return arr; 25 | } 26 | 27 | public static void main(String args[]) { 28 | int arr[] = {11, 8, 23, 5, 10, 12, 2, 14, 11, 9, 4, 4, 6, 24}; 29 | System.out.println("Before : "+Arrays.toString(arr)); 30 | 31 | int result[] = shellSort(arr); 32 | 33 | System.out.println("After : "+Arrays.toString(result)); 34 | } 35 | } -------------------------------------------------------------------------------- /sortingAlgo/shellSort/ShellSort.py: -------------------------------------------------------------------------------- 1 | def shellSort(arr): 2 | n = len(arr) 3 | gap = n/2 4 | 5 | while gap > 0: 6 | 7 | for i in range(gap,n): 8 | temp = arr[i] 9 | j = i 10 | while j >= gap and arr[j-gap] >temp: 11 | arr[j] = arr[j-gap] 12 | j -= gap 13 | 14 | arr[j] = temp 15 | gap /= 2 16 | 17 | 18 | # Driver code to test above 19 | arr = [ 12, 34, 54, 2, 3] 20 | 21 | n = len(arr) 22 | print ("Array before sorting:") 23 | for i in range(n): 24 | print(arr[i]), 25 | 26 | shellSort(arr) 27 | 28 | print ("\nArray after sorting:") 29 | for i in range(n): 30 | print(arr[i]), -------------------------------------------------------------------------------- /sortingAlgo/shellSort/shellSort.lua: -------------------------------------------------------------------------------- 1 | --- Sort an array using the shell sort algorithm. 2 | --- @param t table 3 | --- @return table 4 | local function shellSort(t) 5 | local n = #t 6 | local gap = math.floor(n / 2) 7 | while gap > 0 do 8 | for i = gap + 1, n do 9 | local item = t[i] 10 | local j = i - gap 11 | while j > 0 and t[j] > item do 12 | t[j + gap] = t[j] 13 | j = j - gap 14 | end 15 | t[j + gap] = item 16 | end 17 | gap = math.floor(gap / 2) 18 | end 19 | return t 20 | end 21 | 22 | return shellSort --------------------------------------------------------------------------------