├── Basic Arithmetic ├── Add 2 numbers.java ├── AreaUsingFunctionOverloading.cpp ├── ArmStrongLimit.java ├── Armstrong.java ├── Calculator.c ├── Calculator.py ├── CircularPrime.java ├── EulerTotientFunction.java ├── EvenorOdd.java ├── Fascinating.java ├── Fibonacci_Series.c ├── GetPrimeFactors.cpp ├── NumberOfPointsInsideACircle.cpp ├── Palindrome.c ├── SmithNumber.java ├── add-two-number.py ├── area.java ├── calculator.java ├── dfs.cpp ├── gcdAndLcm.java ├── gcdandlcm.cpp ├── max_two_num.c └── maxof2nos.c ├── Codechef Problems ├── Chef_in_infinte_plane.cpp ├── CouponSystem.cpp ├── MagicalCandyScore.cpp ├── Maximise_the_Subsequence_Sum.java ├── Say No to Palindromes.java ├── Simple_Statistics.cpp ├── Smallest_Numbers_of_Notes.cpp ├── Water_trap.cpp └── fibanacci numbers by replacing prime numbers and multiples of 5 by 0.py ├── Codeforces_Problem ├── A_Arithmetic_Array.cpp ├── A_Variety_Of_Operations.py ├── B_Putting_Plates.cpp ├── Challenging Cliffs.java ├── D_Deleting Divisors.java ├── Merge_Sorted_list.cpp └── Soldier_and_Badges.cpp ├── LeetCode Problems ├── MinimumNumberOfOperationsToMoveAllBallsToEachBox.cpp ├── NumberOfPointsInsideACircle.cpp ├── SubrectangleQueries.cpp └── VowelSpellChecker.cpp ├── PatternPrograms ├── ArrowPattern.java ├── DiamondPattern.cpp ├── DiamondPattern.java ├── Diamondpattern.c ├── FloydTriangle.c ├── Numbers_Rectangle_with_diamond_hollow_pattern.java ├── PascalsTriangle.java ├── Pyramid.cpp ├── Rectangle.java ├── ReveresedPyramid.java ├── RhombusPattern.java ├── RightTriangle.java ├── SandglassStarPattern.java ├── Star_Pattern.java ├── Triangle_Pattern_using_ordered_letters_and_numbers.java ├── W_alphabet.py ├── indiaMap_pattern.java ├── numberpyramid.java ├── pattern.java ├── pattern_of_alphabets.py ├── pyramid.py ├── rectangle_pattern.c └── squarepattern.c ├── README.md ├── Recursion ├── ArmstrongNumber.java ├── Binary_Exponentiation.cpp ├── CombinationsInAStringOfDigits.java ├── Factorial_Rec.cpp ├── Factorial_Rec.java ├── Factorial_Rec.py ├── Fibonacci.cs ├── FibonacciI_recusrion.c ├── Fibonacci_Rec.java ├── Fibonacci_recursive.py ├── GCD_Rec.cpp ├── GCD_Rec.java ├── LeafNodesInBinaryTree.java ├── Predict-the-Winner.java ├── Reverse-String.java ├── Tower of Hanoi.java ├── Tower of Hanoi.js ├── TowerOfHanoi.py ├── binomial_coefiicient.py ├── josephus.java ├── string_reverse_using_recursion.cpp └── sudoku.py ├── Searching ├── Binary Search │ ├── BinarySearch.cs │ ├── BinarySearch.java │ ├── BinarySearch.kt │ ├── BinarySearch.py │ ├── Binary_search.c │ ├── Order Agnostic Binary Search.java │ ├── binary_search.cpp │ └── main.dart ├── Jump Search │ ├── JumpSearch.cpp │ ├── JumpSearch.cs │ ├── JumpSearch.java │ └── JumpSearch.py ├── Linear Search │ ├── Linear Search.kt │ ├── Linear search.py │ ├── LinearSearch.cs │ ├── Linear_search.c │ ├── linearsearch.cpp │ └── linearsearch.go └── Searching.iml ├── Sorting ├── Bubble Sort │ ├── BubbleSort.c │ ├── BubbleSort.java │ ├── BubbleSort.js │ ├── BubbleSort.php │ ├── Bubblesort.cpp │ └── Bubblesort.py ├── BucketSorting │ └── bucket sort.cpp ├── CountingSort │ ├── CountingSort.cs │ ├── CountingSort.js │ ├── CountingSort.kt │ ├── CountingSort.py │ ├── Counting_sort.c │ ├── countingsort.cpp │ └── countingsort.java ├── Cycle Sort │ ├── CycleSort.c │ ├── CycleSort.js │ ├── Cyclesort.cpp │ ├── Cyclesort.java │ └── cyclesort_python.py ├── Heap Sort │ ├── HeapSort.cpp │ ├── HeapSort.cs │ ├── HeapSort.java │ ├── HeapSort.js │ └── HeapSort.py ├── Insertion Sort │ ├── InsertionSort.c │ ├── InsertionSort.java │ ├── InsertionSort.js │ ├── InsertionSort.py │ └── Insertionsort.cpp ├── Merge Sort │ ├── MergeSort.java │ ├── MergeSort.kt │ ├── MergeSort.py │ ├── mergesort.cpp │ └── mergesort.go ├── Quick Sort │ ├── QuickSort.c │ ├── QuickSort.cpp │ ├── QuickSort.cs │ ├── QuickSort.java │ └── QuickSort.py ├── Radix Sort │ ├── RadixSort.cpp │ ├── RadixSort.cs │ └── RadixSort.java ├── Selection Sort │ ├── SelctionSort.java │ ├── SelectionSort.cpp │ ├── SelectionSort.cs │ ├── SelectionSort.kt │ └── selectionsort.py ├── Shell Sort │ └── Shell Sorting.cpp └── Tim Sort │ └── Tim Sort.py ├── StringPrograms ├── Boyer Moore.cpp ├── Boyer Moore.java ├── Boyer Moore.py ├── DecimalToHexadecimal.java ├── Expression.java ├── FindDuplicates.java ├── KMP.cpp ├── Longest_Common_Subsequence.java ├── Longest_Common_Subsequence.py ├── Longest_common_substring.java ├── Pangram.java ├── PermutationOfPalindrome.java ├── RabinKarp.cpp ├── RabinKarp.java ├── RabinKarp.py ├── Recursionfirstcapital.java ├── RomanToInteger.java ├── Shuffle String.py ├── SimpleTextEditor.cpp ├── Special Character At End.java ├── StringPalindrome.py ├── Valid_Anagram.cpp ├── Z Algorithm.cpp ├── Z Algorithm.java ├── Z Algorithm.js ├── Z Algorithm.py ├── firstCapital.java ├── reverse_string.js ├── reversestring.java ├── string_palindrome.java └── zig_zag_string.cpp └── hotel_AP.java /Basic Arithmetic/Add 2 numbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | class AddTwoNumbers { 4 | 5 | public static void main(String[] args) { 6 | Scanner sc = new Scanner(System.in); 7 | System.out.println("Enter two numbers = "); 8 | int num1 = sc.nextInt(); 9 | int num2 = sc.nextInt(); 10 | int sum = num1 + num2; 11 | System.out.println("Sum of these numbers: " + sum); 12 | sc.close(); 13 | } 14 | } -------------------------------------------------------------------------------- /Basic Arithmetic/AreaUsingFunctionOverloading.cpp: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #define pi 3.14 4 | 5 | using namespace std; 6 | float area(float radius) 7 | { 8 | return pi*radius*radius; 9 | } 10 | int area(int lenght,int breadth) 11 | { 12 | return lenght*breadth; 13 | } 14 | float area(float base,float height) 15 | { 16 | return 0.5*base*height; 17 | } 18 | 19 | int main() 20 | { 21 | int length,breadth; 22 | float radius,base,height; 23 | 24 | cout<<"Area of Circle"<>radius; 27 | cout<<"Area of Circle "<>length>>breadth; 32 | cout<<"Area of Rectangle "<>base>>height; 37 | cout<<"Area of Triangle "< 0) 21 | { 22 | rem = temp % 10; 23 | sum = sum + (rem * rem * rem); 24 | temp = temp/10; 25 | } 26 | 27 | if(sum == n) 28 | return true; 29 | return false; 30 | } 31 | } -------------------------------------------------------------------------------- /Basic Arithmetic/Armstrong.java: -------------------------------------------------------------------------------- 1 | public class Armstrong { 2 | 3 | public static void main(String[] args) { 4 | 5 | int number = 371, originalNumber, remainder, result = 0; 6 | 7 | originalNumber = number; 8 | 9 | while (originalNumber != 0) 10 | { 11 | remainder = originalNumber % 10; 12 | result += Math.pow(remainder, 3); 13 | originalNumber /= 10; 14 | } 15 | 16 | if(result == number) 17 | System.out.println(number + " is an Armstrong number."); 18 | else 19 | System.out.println(number + " is not an Armstrong number."); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Basic Arithmetic/Calculator.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() { 3 | char op; 4 | double first, second; 5 | printf("Enter an operator (+, -, *, /): "); 6 | scanf("%c", &op); 7 | printf("Enter two operands: "); 8 | scanf("%lf %lf", &first, &second); 9 | 10 | switch (op) { 11 | case '+': 12 | printf("%.1lf + %.1lf = %.1lf", first, second, first + second); 13 | break; 14 | case '-': 15 | printf("%.1lf - %.1lf = %.1lf", first, second, first - second); 16 | break; 17 | case '*': 18 | printf("%.1lf * %.1lf = %.1lf", first, second, first * second); 19 | break; 20 | case '/': 21 | printf("%.1lf / %.1lf = %.1lf", first, second, first / second); 22 | break; 23 | // operator doesn't match any case constant 24 | default: 25 | printf("Error! operator is not correct"); 26 | } 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Basic Arithmetic/Calculator.py: -------------------------------------------------------------------------------- 1 | # This is Simple Calculator using python 2 | ## This function adds two numbers 3 | def add(x, y): 4 | return x + y 5 | 6 | # This function subtracts two numbers 7 | def subtract(x, y): 8 | return x - y 9 | 10 | # This function multiplies two numbers 11 | def multiply(x, y): 12 | return x * y 13 | 14 | # This function divides two numbers 15 | def divide(x, y): 16 | return x / y 17 | 18 | print("Select operation.") 19 | print("1.Add") 20 | print("2.Subtract") 21 | print("3.Multiply") 22 | print("4.Divide") 23 | 24 | while True: 25 | # take input from the user 26 | choice = input("Enter choice(1/2/3/4): ") 27 | 28 | # check if choice is one of the four options 29 | if choice in ('1', '2', '3', '4'): 30 | num1 = float(input("Enter first number: ")) 31 | num2 = float(input("Enter second number: ")) 32 | 33 | if choice == '1': 34 | print(num1, "+", num2, "=", add(num1, num2)) 35 | 36 | elif choice == '2': 37 | print(num1, "-", num2, "=", subtract(num1, num2)) 38 | 39 | elif choice == '3': 40 | print(num1, "*", num2, "=", multiply(num1, num2)) 41 | 42 | elif choice == '4': 43 | print(num1, "/", num2, "=", divide(num1, num2)) 44 | 45 | # check if user wants another calculation 46 | # break the while loop if answer is no 47 | next_calculation = input("Let's do next calculation? (yes/no): ") 48 | if next_calculation == "no": 49 | break 50 | 51 | else: 52 | print("Invalid Input") 53 | -------------------------------------------------------------------------------- /Basic Arithmetic/CircularPrime.java: -------------------------------------------------------------------------------- 1 | class CircularPrime 2 | { 3 | public static boolean isPrime(int n) 4 | { 5 | for(int x = 2;x<=n/2;x++) 6 | { 7 | if(n%x==0) 8 | { 9 | return false; 10 | } 11 | } 12 | return true; 13 | } 14 | public static boolean isCircularPrime(int n) 15 | { 16 | boolean cp=true; 17 | int m=1,t=n; 18 | while(t>=10) 19 | { 20 | t=t/10; 21 | m=m*10; 22 | } 23 | t=n; 24 | while(t!=0) 25 | { 26 | int d=t%m; 27 | t=t%m; 28 | m=m/10; 29 | t=t*10+d; 30 | if(isPrime(t)==false) 31 | { 32 | cp=false; 33 | break; 34 | } 35 | } 36 | if(cp) 37 | { 38 | return true; 39 | } 40 | else 41 | { 42 | return false; 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /Basic Arithmetic/EulerTotientFunction.java: -------------------------------------------------------------------------------- 1 | // A simple java program to calculate 2 | // Euler's Totient Function 3 | import java.io.*; 4 | 5 | class Main { 6 | 7 | // Function to return GCD of a and b 8 | static int gcd(int a, int b) 9 | { 10 | if (a == 0) 11 | return b; 12 | return gcd(b % a, a); 13 | } 14 | 15 | // A simple method to evaluate 16 | // Euler Totient Function 17 | static int phi(int n) 18 | { 19 | int result = 1; 20 | for (int i = 2; i < n; i++) 21 | if (gcd(i, n) == 1) 22 | result++; 23 | return result; 24 | } 25 | 26 | // Driver code 27 | public static void main(String[] args) 28 | { 29 | int n; 30 | 31 | for (n = 1; n <= 10; n++) 32 | System.out.println("phi(" + n + ") = " + phi(n)); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Basic Arithmetic/EvenorOdd.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class EvenorOdd 4 | { 5 | public static void main(String[] args) 6 | { 7 | int n; 8 | Scanner in = new Scanner(System.in); 9 | System.out.print("Enter the number: "); 10 | n = in.nextInt(); 11 | 12 | result(n); 13 | } 14 | 15 | static void result(int n) { 16 | if (n % 2 == 0) 17 | { 18 | System.out.println("Even"); 19 | } 20 | else 21 | { 22 | System.out.println("Odd"); 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /Basic Arithmetic/Fascinating.java: -------------------------------------------------------------------------------- 1 | package com.company; 2 | 3 | import java.util.*; 4 | 5 | public class Fascinating 6 | { 7 | public static void main(String[] args) 8 | { 9 | Scanner sc=new Scanner(System.in); 10 | System.out.println("Input m & n"); 11 | int m=sc.nextInt(); 12 | int n=sc.nextInt(); 13 | int a,b,c; 14 | String s="",f=" ",a1,b1,c1; 15 | int freq=0; 16 | for(int i=m;i 2 | int main() 3 | { 4 | int n,a=0,b=1,nt; 5 | printf("Enter number of terms for Fibonacci Series:"); 6 | scanf("%d",&n); 7 | printf("The Fibonacci Series:"); 8 | for(int i=1;i<=n;++i) 9 | { 10 | printf("%d, ",a); 11 | nt=a+b; 12 | a=b; 13 | b=nt; 14 | } 15 | return 0; 16 | } -------------------------------------------------------------------------------- /Basic Arithmetic/NumberOfPointsInsideACircle.cpp: -------------------------------------------------------------------------------- 1 | 2 | class Solution { 3 | public: 4 | // My Approach - Pretty Basic : Accepted ( faster than only 5% solutions and memory less than 18% solutions) 5 | /*int euc(vector& a , vector& b){ 6 | int ans = 0; 7 | 8 | ans = ceil(sqrt( pow((b[0] - a[0] ), 2) + pow((b[1] - a[1] ), 2))); 9 | 10 | return ans ; 11 | } 12 | vector countPoints(vector>& points, vector>& queries) { 13 | int n = queries.size() ; 14 | vector ans(n, 0) ; 15 | int cnt = 0 ; 16 | 17 | for(int i = 0 ; i < n ; ++i){ 18 | cnt = 0 ; 19 | for(auto s : points){ 20 | if(euc(s , queries[i]) <= queries[i][2]) 21 | ++cnt; 22 | } 23 | ans[i] = cnt ; 24 | } 25 | 26 | return ans ; 27 | }*/ 28 | 29 | //Online Approach - We can improve our runtime if we sort points by x coordinate. 30 | //That way, we only process points in [qx - r, qx + r] interval. We use binary 31 | //search to find the start of that interval. 32 | 33 | //Note that we need to fiddle with data structures here to make it fast. 34 | //Sorting vector of vectors, or using multiset adds noticeable overhead. 35 | 36 | //Answer found from Discussion Tab on LeetCode 37 | 38 | int sqr(int a) { 39 | return a * a; 40 | } 41 | 42 | //find lower bound of left boundry 43 | int find_left_boundry_index(vector > & points , int x_center , int y_center , int r) { 44 | 45 | int lo = 0, hi = points.size(); 46 | 47 | while (lo < hi) { 48 | 49 | int mi = lo + (hi - lo ) / 2; 50 | 51 | if (x_center - r <= points[mi][0]) 52 | hi = mi; 53 | else 54 | lo = mi + 1; 55 | 56 | } 57 | return hi == points.size() or (points[hi][0] > x_center + r or points[hi][0] < x_center - r) ? points.size() : hi; 58 | 59 | } 60 | vector countPoints(vector>& points, vector>& queries) { 61 | 62 | sort(points.begin(), points.end()); 63 | vector ans; 64 | 65 | for (int i = 0; i < queries.size(); i++) { 66 | 67 | int x_center = queries[i][0], y_center = queries[i][1], r = queries[i][2]; 68 | int index = find_left_boundry_index(points, x_center , y_center, r); 69 | int count = 0; 70 | 71 | for (int j = index; j < points.size() and points[j][0] <= x_center + r; j++) { 72 | 73 | int x = points[j][0]; 74 | int y = points[j][1]; 75 | // square of distance from center 76 | count += sqr(x_center - x) + sqr(y_center - y) <= r * r; 77 | } 78 | 79 | ans.push_back(count); 80 | } 81 | return ans; 82 | } 83 | }; 84 | -------------------------------------------------------------------------------- /Basic Arithmetic/Palindrome.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int Number, Temp, Reminder, Reverse = 0; 6 | 7 | printf("\nPlease Enter any number to Check for Palindrome\n"); 8 | scanf("%d", &Number); 9 | 10 | //Helps to prevent altering the original value 11 | Temp = Number; 12 | 13 | while ( Temp > 0) 14 | { 15 | Reminder = Temp %10; 16 | Reverse = Reverse *10+ Reminder; 17 | Temp = Temp /10; 18 | } 19 | 20 | printf("Reverse of entered number is = %d\n", Reverse); 21 | 22 | if ( Number == Reverse ) 23 | printf("\n%d is Palindrome Number.\n", Number); 24 | 25 | else 26 | printf("%d is not the Palindrome Number.\n", Number); 27 | 28 | return 0; 29 | } -------------------------------------------------------------------------------- /Basic Arithmetic/SmithNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class SmithNumber 3 | { 4 | public int digitSum(int n) 5 | { 6 | int sum = 0; 7 | for(int x = n ; x!=0 ; x/=10) 8 | { 9 | sum+=x%10; 10 | } 11 | return sum; 12 | } 13 | public static void main(String[]args) 14 | { 15 | Scanner sc = new Scanner(System.in); 16 | SmithNumber ob = new SmithNumber(); 17 | System.out.println("Enter any number"); 18 | int n = sc.nextInt(); 19 | 20 | int s1 = ob.digitSum(n); 21 | int s2=0; 22 | int d = 2; 23 | while(n>1) 24 | { 25 | if(n%d==0) 26 | { 27 | n/=d; 28 | s2+=ob.digitSum(d); 29 | } 30 | else 31 | { 32 | d++; 33 | } 34 | } 35 | 36 | if(s1==s2) 37 | System.out.println("Smith Number"); 38 | else 39 | System.out.println("Not a smith number"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Basic Arithmetic/add-two-number.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # SPDX-License-Identifier: GPL-3.0-or-later 3 | # (c) TechyMinati ( Aryan Sinha ) 4 | # This program adds two numbers 5 | 6 | # Take Input from user 7 | num1 = int(input(" Enter First Number")) 8 | num2 = int(input(" Enter Second Number")) 9 | 10 | # Add two numbers given by the user 11 | sum = num1 + num2 12 | 13 | # Output of the above sum 14 | print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) 15 | -------------------------------------------------------------------------------- /Basic Arithmetic/area.java: -------------------------------------------------------------------------------- 1 | 2 | // Program to calculate area of rectangle, square, triangle 3 | 4 | import java.io.*; 5 | import java.util.*; 6 | 7 | class area 8 | { 9 | public static void main(String args[]) 10 | { 11 | int rectlen,rectbr,triheight,tribase,sqsize; 12 | float cirpi,cirradius; 13 | 14 | Scanner rectobj = new Scanner(System.in); 15 | Scanner sqobj = new Scanner(System.in); 16 | Scanner triobj = new Scanner(System.in); 17 | Scanner cirobj = new Scanner(System.in); 18 | 19 | System.out.print("Enter the value of Length of Rectangle - "); 20 | rectlen = rectobj.nextInt(); 21 | System.out.print("Enter the value of Breadth of Rectangle - "); 22 | rectbr = rectobj.nextInt(); 23 | 24 | System.out.print("Enter the value of Size of Square - "); 25 | sqsize = sqobj.nextInt(); 26 | 27 | System.out.print("Enter the value of Height of Triangle - "); 28 | triheight = triobj.nextInt(); 29 | System.out.print("Enter the value of Base of Triangle - "); 30 | tribase = triobj.nextInt(); 31 | 32 | System.out.print("Enter the value of Pi - "); 33 | cirpi = cirobj.nextFloat(); 34 | System.out.print("Enter the value of Radius of Circle - "); 35 | cirradius = cirobj.nextFloat(); 36 | 37 | 38 | System.out.println("Area of rectangle = "+(rectlen*rectbr)); 39 | System.out.println("Area of square = "+(sqsize*sqsize)); 40 | System.out.println("Area of triangle = "+((triheight*tribase)/2)); 41 | System.out.println("Area of circle = "+(cirpi*cirradius*cirradius)); 42 | } 43 | } 44 | 45 | 46 | /* 47 | C --- scanf, getch, getchar (stdio.h, conio.h) 48 | C++ --- cin (iostream.h) 49 | 50 | functions - already defined in the library 51 | 52 | Scanner object1 = new Scanner(System.in); 53 | 54 | object1.readInt(); 55 | 56 | */ 57 | 58 | -------------------------------------------------------------------------------- /Basic Arithmetic/calculator.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class calculator { 3 | public static void main(String[] args) throws Exception { 4 | 5 | 6 | Scanner sc=new Scanner(System.in); 7 | 8 | System.out.println("----------WELCOME TO CALCULATOR-----------"); 9 | 10 | System.out.println("Enter two numbers A and B"); 11 | System.out.print("A: "); 12 | int a=sc.nextInt(); 13 | System.out.print("B: "); 14 | int b=sc.nextInt(); 15 | 16 | System.out.println("Choose Arithemetic Operation"); 17 | System.out.println("Enter * to multiplication"); 18 | System.out.println("Enter + for addition"); 19 | System.out.println("Enter - for subtraction"); 20 | System.out.println("Enter / for division "); 21 | 22 | String ch=sc.next(); 23 | if(ch.equals("*")){ 24 | 25 | System.out.println(a*b); 26 | } 27 | else if(ch.equals("+")){ 28 | 29 | System.out.println(a+b); 30 | 31 | } 32 | else if(ch.equals("-")){ 33 | 34 | System.out.println(a-b); 35 | } 36 | else if(ch.equals("/")){ 37 | System.out.println((double)a/(double)b); 38 | } 39 | else{ 40 | System.out.println("invalid selection"); 41 | } 42 | 43 | 44 | 45 | 46 | 47 | 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /Basic Arithmetic/dfs.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to print DFS traversal from 2 | // a given vertex in a given graph 3 | #include 4 | using namespace std; 5 | 6 | // Graph class represents a directed graph 7 | // using adjacency list representation 8 | class Graph 9 | { 10 | public: 11 | map visited; 12 | map> adj; 13 | 14 | // function to add an edge to graph 15 | void addEdge(int v, int w); 16 | 17 | // DFS traversal of the vertices 18 | // reachable from v 19 | void DFS(int v); 20 | }; 21 | 22 | void Graph::addEdge(int v, int w) 23 | { 24 | adj[v].push_back(w); // Add w to v’s list. 25 | } 26 | 27 | void Graph::DFS(int v) 28 | { 29 | // Mark the current node as visited and 30 | // print it 31 | visited[v] = true; 32 | cout << v << " "; 33 | 34 | // Recur for all the vertices adjacent 35 | // to this vertex 36 | list::iterator i; 37 | for (i = adj[v].begin(); i != adj[v].end(); ++i) 38 | if (!visited[*i]) 39 | DFS(*i); 40 | } 41 | 42 | // Driver code 43 | int main() 44 | { 45 | // Create a graph given in the above diagram 46 | Graph g; 47 | g.addEdge(0, 1); 48 | g.addEdge(0, 2); 49 | g.addEdge(1, 2); 50 | g.addEdge(2, 0); 51 | g.addEdge(2, 3); 52 | g.addEdge(3, 3); 53 | 54 | cout << "Following is Depth First Traversal" 55 | " (starting from vertex 2) \n"; 56 | g.DFS(2); 57 | 58 | return 0; 59 | } 60 | 61 | // improved by Vishnudev C 62 | -------------------------------------------------------------------------------- /Basic Arithmetic/gcdAndLcm.java: -------------------------------------------------------------------------------- 1 | package main; 2 | 3 | import java.util.Scanner; 4 | 5 | public class hcf_and_lcm { 6 | 7 | public static void main(String[] args) { 8 | 9 | Scanner in=new Scanner(System.in); 10 | int a = in.nextInt(); 11 | int b = in.nextInt(); 12 | 13 | int answer=hcf(a,b); 14 | System.out.println(answer); 15 | int result=lcm(a,b); 16 | System.out.println(result); 17 | } 18 | 19 | static int hcf(int n1 ,int n2) { 20 | 21 | int original_n1,original_n2; 22 | 23 | while(n1%n2!=0) { 24 | int rem = n1%n2; 25 | n1=n2; 26 | n2=rem; 27 | 28 | 29 | } 30 | 31 | int hcf=n2; 32 | // System.out.println("The hcf of 2 given number is "+ hcf); 33 | 34 | 35 | 36 | 37 | return hcf; 38 | } 39 | 40 | static int lcm(int n1 ,int n2) { 41 | 42 | int original_n1,original_n2; 43 | 44 | while(n1%n2!=0) { 45 | int rem = n1%n2; 46 | n1=n2; 47 | n2=rem; 48 | 49 | 50 | } 51 | 52 | int hcf=n2; 53 | 54 | 55 | int lcm=(n1*n2)/hcf; 56 | // System.out.println("The LCM of 2 given numbers is "+ lcm); 57 | 58 | 59 | return lcm; 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /Basic Arithmetic/gcdandlcm.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int gcd(int x, int y) 8 | { 9 | int r = 0, a, b; 10 | a = (x > y) ? x : y; // a is greater number 11 | b = (x < y) ? x : y; // b is smaller number 12 | 13 | r = b; 14 | while (a % b != 0) 15 | { 16 | r = a % b; 17 | a = b; 18 | b = r; 19 | } 20 | return r; 21 | } 22 | 23 | int lcm(int x, int y) 24 | { 25 | int a; 26 | a = (x > y) ? x : y; // a is greater number 27 | while (true) 28 | { 29 | if (a % x == 0 && a % y == 0) 30 | return a; 31 | ++a; 32 | } 33 | } 34 | 35 | int main(int argc, char **argv) 36 | { 37 | cout << "Enter the two numbers: "; 38 | int x, y; 39 | cin >> x >> y; 40 | cout << "The GCD of two numbers is: " << gcd(x, y) << endl; 41 | ; 42 | cout << "The LCM of two numbers is: " << lcm(x, y) << endl; 43 | ; 44 | return 0; 45 | } -------------------------------------------------------------------------------- /Basic Arithmetic/max_two_num.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | int main() 5 | { 6 | int num1, num2; 7 | 8 | 9 | printf("Enter Two Numbers: "); 10 | scanf("%d%d", &num1, &num2); 11 | 12 | 13 | if(num1 > num2) 14 | { 15 | printf("%d is maximum", num1); 16 | } 17 | 18 | 19 | if(num2 > num1) 20 | { 21 | printf("%d is maximum", num2); 22 | } 23 | 24 | 25 | if(num1 == num2) 26 | { 27 | printf("Both are equal"); 28 | } 29 | 30 | return 0; 31 | } -------------------------------------------------------------------------------- /Basic Arithmetic/maxof2nos.c: -------------------------------------------------------------------------------- 1 | /** 2 | * C program to find maximum between two numbers 3 | */ 4 | 5 | #include 6 | 7 | int main() 8 | { 9 | int num1, num2; 10 | 11 | /* Input two numbers from user */ 12 | printf("Enter two numbers: "); 13 | scanf("%d%d", &num1, &num2); 14 | 15 | /* If num1 is maximum */ 16 | if(num1 > num2) 17 | { 18 | printf("%d is maximum", num1); 19 | } 20 | 21 | /* If num2 is maximum */ 22 | if(num2 > num1) 23 | { 24 | printf("%d is maximum", num2); 25 | } 26 | 27 | /* Additional condition check for equality */ 28 | if(num1 == num2) 29 | { 30 | printf("Both are equal"); 31 | } 32 | 33 | return 0; 34 | } -------------------------------------------------------------------------------- /Codechef Problems/Chef_in_infinte_plane.cpp: -------------------------------------------------------------------------------- 1 | // Problem Link : https://www.codechef.com/COOK131B/problems/CHFPLN/ 2 | // Problem : Chef in infinite plates 3 | // July cook-off 2021 4 | // Solution : 5 | 6 | #include 7 | using namespace std; 8 | #define ll long long int 9 | #define F(i, a, b) for (long long i = a; i < b; i++) 10 | #define RF(i, a, b) for (long long i = a; i >= b; i--) 11 | 12 | int main() 13 | { 14 | ios_base::sync_with_stdio(false); 15 | cin.tie(NULL); 16 | cout.tie(NULL); 17 | 18 | int test_case = 1; 19 | cin >> test_case; 20 | while (test_case--){ 21 | 22 | int n; 23 | cin>>n; 24 | int a[n]; 25 | mapmp; 26 | F(i,0,n){ 27 | cin>>a[i]; 28 | mp[a[i]]++; 29 | } 30 | int cnt=0; 31 | for(auto x:mp){ 32 | cnt+=min(x.second,x.first-1); 33 | } 34 | cout< 2 | #include 3 | #include 4 | #include 5 | 6 | using namespace std; 7 | 8 | long long int t; 9 | int main() { 10 | cin >> t; 11 | for(int i9 = 0; i9 < t; i9++){ 12 | int n; 13 | cin >> n; 14 | int c1[n], c2[n], c3[n], d1[n], d2[n], d3[n]; 15 | int j1 = 0, j2 = 0, j3 = 0; 16 | int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN; 17 | for(int i = 0 ; i < n ; i++){ 18 | int ci, le, di; 19 | cin >> ci >> le >> di; 20 | //cout << ci << " " << le << " " << di << endl; 21 | if(le == 1){ 22 | if (max1 < di){ 23 | max1 = di; 24 | } 25 | c1[j1] = ci; 26 | d1[j1] = di; 27 | j1++; 28 | } 29 | else if( le == 2){ 30 | if (max2 < di){ 31 | max2 = di; 32 | } 33 | c2[j2] = ci; 34 | d2[j2] = di; 35 | j2++; 36 | } 37 | else { 38 | if (max3 < di){ 39 | max3 = di; 40 | } 41 | c3[j3] = ci; 42 | d3[j3] = di; 43 | j3++; 44 | } 45 | } 46 | int x = 0, y = 0, z = 0; 47 | int ans1[n], ans2[n], ans3[n]; 48 | for(int i = 0; i < j1; i++){ 49 | if (d1[i] == max1){ 50 | ans1[x] = c1[i]; 51 | x++; 52 | } 53 | 54 | } 55 | int* a1; 56 | a1 = min_element(ans1, ans1 + x); 57 | cout << max1 << " " << *a1 << endl; 58 | for(int i = 0; i < j2; i++){ 59 | if (d2[i] == max2){ 60 | ans2[y] = c2[i]; 61 | y++; 62 | } 63 | 64 | } 65 | int* a2; 66 | a2 = min_element(ans2, ans2 + y); 67 | cout << max2 << " " << *a2 << endl; 68 | for(int i = 0; i < j3; i++){ 69 | if (d3[i] == max3){ 70 | ans3[z] = c3[i]; 71 | z++; 72 | } 73 | 74 | } 75 | int* a3; 76 | a3 = min_element(ans3, ans3 + z); 77 | cout << max3 << " " << *a3 << endl; 78 | } 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /Codechef Problems/Maximise_the_Subsequence_Sum.java: -------------------------------------------------------------------------------- 1 | // Problem Link : https://www.codechef.com/START10C/problems/SIGNFLIP 2 | // Problem : Maximise the Subsequence Sum 3 | 4 | // Solution : 5 | 6 | import java.util.*; 7 | import java.lang.*; 8 | import java.io.*; 9 | 10 | /* Name of the class has to be "Main" only if the class is public. */ 11 | class Codechef 12 | { 13 | public static void main (String[] args) throws java.lang.Exception 14 | { 15 | // your code goes here 16 | try { 17 | Scanner sc = new Scanner(System.in); 18 | int t = sc.nextInt(); 19 | 20 | while(t-- > 0){ 21 | int n = sc.nextInt(); 22 | int k = sc.nextInt(); 23 | int m = n; 24 | int sum = 0; 25 | PriorityQueue arr = new PriorityQueue(); 26 | while(m-- > 0){ 27 | arr.add(sc.nextInt()); 28 | } 29 | if (k > 0) { 30 | while (k != 0) { 31 | if(arr.peek() < 0) { 32 | int r = arr.poll() * -1; 33 | sum = sum + r; 34 | k--; 35 | } else { 36 | k = 0; 37 | } 38 | } 39 | while(arr.size() != 0) { 40 | if(arr.peek() < 0) { 41 | arr.poll(); 42 | }else{ 43 | int r = arr.poll(); 44 | sum = sum + r; 45 | } 46 | 47 | } 48 | }else{ 49 | while(arr.size() != 0){ 50 | if (arr.peek() < 0) { 51 | arr.poll() ; 52 | } else { 53 | int r = arr.poll(); 54 | sum = sum + r; 55 | } 56 | } 57 | 58 | } 59 | System.out.println(sum); 60 | } 61 | } catch(Exception e) { 62 | return; 63 | } 64 | 65 | 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /Codechef Problems/Simple_Statistics.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | using namespace std; 6 | 7 | int main() { 8 | int t; 9 | cin >> t; 10 | while(t--) { 11 | int n, k; 12 | cin >> n >> k; 13 | long long int a[n]; 14 | 15 | for(int i =0; i < n; i++){ 16 | cin >> a[i]; 17 | //sum += a[i]; 18 | } 19 | 20 | sort(a,a+n); 21 | long double sum = 0; 22 | for(int i = k ; i < n - k; i++){ 23 | //cout << a[i] << " "; 24 | sum += a[i]; 25 | } 26 | 27 | long double ans = sum/(n - 2 * k); 28 | cout << fixed << setprecision(6) << ans < 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t,n; 7 | 8 | cin>>t; 9 | int count; 10 | while(t--) 11 | { 12 | cin>>n; 13 | 14 | while(n > 100) 15 | { 16 | count = n / 100; 17 | n = n % 100; 18 | //cout<= 50) 21 | { 22 | count += 1; 23 | n = n - 50; 24 | 25 | } 26 | while (n >= 10 and n < 50) 27 | { 28 | count += 1; 29 | n = n - 10; 30 | //cout<= 5 and n < 10) 34 | { 35 | count += 1; 36 | n = n - 5; 37 | //cout<= 2 and n < 5) 40 | { 41 | count += 1; 42 | n = n - 2; 43 | //cout< 0 and n <= 1) 46 | { 47 | count += 1; 48 | n = n - 1; 49 | } 50 | 51 | cout< 2 | #include 3 | using namespace std; 4 | 5 | int main(){ 6 | 7 | vector v{0,1,0,2,1,0,1,3,2,1,2,1}; 8 | int n = v.size(); 9 | 10 | 11 | 12 | vector left(n,0), right(n,0); 13 | 14 | left[0] = v[0]; 15 | right[n-1] = v[n-1]; 16 | 17 | for(int i=1;i 1: 3 | for i in range(2, n // 2 + 1): 4 | if (n % i) == 0: 5 | return False 6 | else: 7 | return True 8 | else: 9 | return False 10 | 11 | def fibonacci(n): 12 | n1, n2 = 1, 1 13 | count = 0 14 | 15 | if n == 1: 16 | print(n1) 17 | else: 18 | while count < n: 19 | if not is_prime(n1) and n1 % 5 != 0: 20 | print(n1, end=' ') 21 | else: 22 | print(0, end=' ') 23 | n3 = n1 + n2 24 | n1 = n2 25 | n2 = n3 26 | count += 1 27 | 28 | n = int(input("Enter the number:")) 29 | fibonacci(n) 30 | -------------------------------------------------------------------------------- /Codeforces_Problem/A_Arithmetic_Array.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int t, n; 7 | 8 | cin>>t; 9 | 10 | while(t--) 11 | { 12 | cin>>n; 13 | 14 | int a[n],sum = 0; 15 | 16 | for (int i = 0; i>a[i]; 19 | sum += a[i]; 20 | } 21 | 22 | if (sum == n) 23 | { 24 | cout<<0< n) 28 | { 29 | cout< 7 | using namespace std; 8 | #define ll long long int 9 | #define F(i, a, b) for (long long i = a; i < b; i++) 10 | #define RF(i, a, b) for (long long i = a; i >= b; i--) 11 | #define pb push_back 12 | 13 | int main() 14 | { 15 | ios_base::sync_with_stdio(false); 16 | cin.tie(NULL); 17 | cout.tie(NULL); 18 | 19 | int test_case = 1; 20 | cin >> test_case; 21 | while (test_case--){ 22 | 23 | int n,m; 24 | cin>>n>>m; 25 | 26 | int b[n][m]; 27 | F(i,0,n) 28 | F(j,0,m) 29 | b[i][j]=0; 30 | 31 | int dx[8]={1,-1,-1,1,-1,1,0,0}; 32 | int dy[8]={1,-1,1,-1,0,0,-1,1}; 33 | 34 | for(int i=0;i=0 && i+dx[k]=0 && m-1+dy[k]=0 && n-1+dx[k]=0 && i+dy[k]a) return b-a; 50 | return a-b; 51 | } 52 | 53 | public static char nextChar(char curr) { 54 | if(curr == 'z') return 'a'; 55 | else return (char)((int)curr+1); 56 | } 57 | 58 | public static int factorial(int i) { 59 | int res = 1; 60 | while(i>0) res*=i--; 61 | return res; 62 | } 63 | 64 | static HashSet cache = new HashSet<>(); 65 | public static void main (String[] args) throws java.lang.Exception 66 | { 67 | FastReader fs = new FastReader(); 68 | int t = fs.nextInt(); 69 | while(t-->0) { 70 | int n = fs.nextInt(); 71 | String A = "Alice"; 72 | String B = "Bob"; 73 | if (n%2==1 || n==2 || n==8 || n==32 ||n==128 ||n==512 || n==2048 ||n==8192||n==32768||n==131072||n==524288|| n==2097152||n==8388608||n==33554432||n==134217728||n==536870912) 74 | System.out.println(B); 75 | else 76 | System.out.println(A); 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /Codeforces_Problem/Merge_Sorted_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class node{ 5 | 6 | public: 7 | int data; 8 | node* next; 9 | 10 | node(int data){ 11 | this->data = data; 12 | next = NULL; 13 | } 14 | }; 15 | 16 | void insertathead(node* &head,int data){ 17 | if(head == NULL){ 18 | head = new node(data); 19 | return; 20 | } 21 | 22 | node* n = new node(data); 23 | n->next = head; 24 | head = n; 25 | } 26 | 27 | void print(node * head){ 28 | while(head!=NULL){ 29 | cout<data<<"-->"; 30 | head = head->next; 31 | } 32 | cout<data < b->data){ 47 | c=a; 48 | c->next = merge(a->next,b); 49 | }else{ 50 | c=b; 51 | c->next = merge(a,b->next); 52 | } 53 | return c; 54 | } 55 | 56 | 57 | int main(){ 58 | 59 | node* a = NULL; 60 | insertathead(a,10); 61 | insertathead(a,7); 62 | insertathead(a,5); 63 | insertathead(a,1); 64 | 65 | node* b = NULL; 66 | insertathead(b,6); 67 | insertathead(b,3); 68 | insertathead(b,2); 69 | 70 | node* head = merge(a,b); 71 | 72 | print(head); 73 | return 0; 74 | } -------------------------------------------------------------------------------- /Codeforces_Problem/Soldier_and_Badges.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Luvdipsingh Dadiyala 5 | 6 | #define db1(x) cout<<#x<<"="<= 1; a--) { 31 | for (b = a; b <= rows; b++) { 32 | System.out.print(" "); 33 | } 34 | for (c = 1; c < a; c++) { 35 | System.out.print("#"); 36 | } 37 | System.out.println(""); 38 | } 39 | sc.close(); 40 | } 41 | } -------------------------------------------------------------------------------- /PatternPrograms/DiamondPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n, c, k, space = 1; 6 | cout<<"\n Enter Number of Rows : "; 7 | cin>>n; 8 | space = n - 1; 9 | for(k = 1; k<=n; k++) 10 | { 11 | for (c = 1; c<=space; c++) 12 | cout<<" "; 13 | space--; 14 | for (c = 1; c<= 2*k-1; c++) 15 | cout<<"*"; 16 | cout<<"\n"; 17 | } 18 | space = 1; 19 | for(k = 1; k<= n - 1; k++) 20 | { 21 | for (c = 1; c<= space; c++) 22 | cout<<" "; 23 | space++; 24 | for (c = 1 ; c<= 2*(n-k)-1; c++) 25 | cout<<"*"; 26 | cout<<"\n"; 27 | } 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /PatternPrograms/DiamondPattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | public class Diamond 3 | { 4 | public static void main(String args[]) 5 | { 6 | int n, i, j, space = 1; 7 | System.out.print("Enter the number of rows: "); 8 | Scanner s = new Scanner(System.in); 9 | n = s.nextInt(); 10 | space = n - 1; 11 | for (j = 1; j <= n; j++) 12 | { 13 | for (i = 1; i <= space; i++) 14 | { 15 | System.out.print(" "); 16 | } 17 | space--; 18 | for (i = 1; i <= 2 * j - 1; i++) 19 | { 20 | System.out.print("*"); 21 | } 22 | System.out.println(""); 23 | } 24 | space = 1; 25 | for (j = 1; j <= n - 1; j++) 26 | { 27 | for (i = 1; i <= space; i++) 28 | { 29 | System.out.print(" "); 30 | } 31 | space++; 32 | for (i = 1; i <= 2 * (n - j) - 1; i++) 33 | { 34 | System.out.print("*"); 35 | } 36 | System.out.println(""); 37 | } 38 | } 39 | } -------------------------------------------------------------------------------- /PatternPrograms/Diamondpattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n, c, k; 5 | 6 | printf("Enter number of rows\n"); 7 | scanf("%d", &n); 8 | 9 | for (k = 1; k <= n; k++) 10 | { 11 | for (c = 1; c <= n-k; c++) 12 | printf(" "); 13 | 14 | for (c = 1; c <= 2*k-1; c++) 15 | printf("*"); 16 | 17 | printf("\n"); 18 | } 19 | 20 | for (k = 1; k <= n - 1; k++) 21 | { 22 | for (c = 1; c <= k; c++) 23 | printf(" "); 24 | 25 | for (c = 1 ; c <= 2*(n-k)-1; c++) 26 | printf("*"); 27 | 28 | printf("\n"); 29 | } 30 | 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /PatternPrograms/FloydTriangle.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int r, i, j; 6 | int k = 1; 7 | printf("Enter number of rows\n"); 8 | scanf("%d", &r); 9 | for (i = 1; i <= r; i++) 10 | { 11 | for (j = 1; j <= i; j++) 12 | { 13 | printf("%d ", k++); 14 | } 15 | printf("\n"); 16 | } 17 | return 0; 18 | } -------------------------------------------------------------------------------- /PatternPrograms/Numbers_Rectangle_with_diamond_hollow_pattern.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class Numbers_Rectangle_with_diamond_hollow_pattern{ 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | int i,j,k,n; 6 | n=5;//n = sc.nextInt(); 7 | int countSpace=0; 8 | for(i=n;i>0;i--) { 9 | for(k=1;k<=i;k++) 10 | System.out.print(n-k+1); 11 | for(j=0;j<2*n-2*i-1;j++) { 12 | System.out.print(" "); 13 | } 14 | countSpace++; 15 | if(i==n) 16 | for(k=i-1;k>=1;k--) 17 | System.out.print(k); 18 | else 19 | for(k=i;k>=1;k--) 20 | System.out.print(k); 21 | System.out.println(); 22 | } 23 | countSpace=n-1; 24 | for(i=2;i<=n;i++) { 25 | for(k=1;k<=i;k++) 26 | System.out.print(n-k+1); 27 | for(j=0;j<2*n-2*i-1;j++) { 28 | System.out.print(" "); 29 | } 30 | countSpace--; 31 | if(i==n) 32 | for(k=i-1;k>=1;k--) 33 | System.out.print(k); 34 | else 35 | for(k=i;k>=1;k--) 36 | System.out.print(k); 37 | System.out.println(); 38 | } 39 | 40 | } 41 | } 42 | /* 43 | Output: 44 | 45 | 543214321 46 | 5432 4321 47 | 543 321 48 | 54 21 49 | 5 1 50 | 54 21 51 | 543 321 52 | 5432 4321 53 | 543214321 54 | 55 | */ -------------------------------------------------------------------------------- /PatternPrograms/PascalsTriangle.java: -------------------------------------------------------------------------------- 1 | // Print Pascal's Triangle in Java 2 | import java.io.*; 3 | 4 | class GFG { 5 | public int factorial(int i) 6 | { 7 | if (i == 0) 8 | return 1; 9 | return i * factorial(i - 1); 10 | } 11 | public static void main(String[] args) 12 | { 13 | int n = 4, i, j; 14 | GFG g = new GFG(); 15 | for (i = 0; i <= n; i++) { 16 | for (j = 0; j <= n - i; j++) { 17 | 18 | // for left spacing 19 | System.out.print(" "); 20 | } 21 | for (j = 0; j <= i; j++) { 22 | 23 | // nCr formula 24 | System.out.print( 25 | " " 26 | + g.factorial(i) 27 | / (g.factorial(i - j) 28 | * g.factorial(j))); 29 | } 30 | 31 | // for newline 32 | System.out.println(); 33 | } 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /PatternPrograms/Pyramid.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | int main() 6 | { 7 | int n; 8 | cout<<"Enter Number of Rows : "; 9 | cin>>n; 10 | for(int i=1, k=0; i<=n; i++, k=0) 11 | { 12 | for(int j=1; j<=(n-i); j++) 13 | { 14 | cout<<" "; 15 | } 16 | while(k!=(2*i)-1) 17 | { 18 | cout<<"*"; 19 | k++; 20 | } 21 | cout< n ? 2*n-row : row ; 25 | 26 | int howmuchSpace = n-uptowhatCol; 27 | 28 | for(int space=1;space<= howmuchSpace ; space++) { 29 | System.out.print(" "); 30 | } 31 | 32 | for (int col = 1; col <= uptowhatCol; col++) { 33 | 34 | System.out.print("* "); 35 | 36 | } 37 | System.out.println(); 38 | 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /PatternPrograms/RightTriangle.java: -------------------------------------------------------------------------------- 1 | class RightTriangle 2 | { 3 | public static void main(String[]args) 4 | { 5 | for(int x = 3 ; x<=7 ; x++) 6 | { 7 | for(int y = x ; y<=6 ; y++) 8 | { 9 | System.out.print(" "); 10 | } 11 | for(int y = 3 ; y<=x ; y++) 12 | { 13 | System.out.print(y); 14 | } 15 | System.out.println(); 16 | } 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /PatternPrograms/SandglassStarPattern.java: -------------------------------------------------------------------------------- 1 | * * * * * 2 | * * * * 3 | * * * 4 | * * 5 | * 6 | * 7 | * * 8 | * * * 9 | * * * * 10 | * * * * * 11 | 12 | 13 | 14 | 15 | 16 | import java.util.Scanner; 17 | public class Himanshu 18 | { 19 | public static void main(String[] args) 20 | { 21 | Scanner sc = new Scanner(System.in); 22 | System.out.println("Enter the number of rows: "); 23 | 24 | int rows = sc.nextInt(); 25 | for (int i= 0; i<= rows-1 ; i++) 26 | { 27 | for (int j=0; j = 0; i--) 37 | { 38 | for (int j=0; j< i ;j++) 39 | { 40 | System.out.print(" "); 41 | } 42 | for (int k=i; k<=rows-1; k++) 43 | { 44 | System.out.print("*" + " "); 45 | } 46 | System.out.println(""); 47 | } 48 | sc.close(); 49 | } 50 | } -------------------------------------------------------------------------------- /PatternPrograms/Star_Pattern.java: -------------------------------------------------------------------------------- 1 | public class JavaPattern { 2 | public static void main(String[] args) { 3 | int i,j, rows=10; 4 | 5 | //upper half 6 | for(i=rows; i>=1; i--) { 7 | for (j = 1; j <= i; j++) { 8 | System.out.print("* "); 9 | if (i == 1) { 10 | for (int a = 1; a <= rows * 2; a++) { 11 | System.out.print("* "); 12 | } 13 | } 14 | } 15 | System.out.println(); 16 | } 17 | 18 | //lower half 19 | for(i=2; i<=rows; i++){ 20 | for(j=1;j<=i; j++){ 21 | System.out.print("* "); 22 | } 23 | System.out.println(); 24 | } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /PatternPrograms/Triangle_Pattern_using_ordered_letters_and_numbers.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class Triangle_Pattern_using_ordered_letters_and_numbers{ 3 | public static void main(String[] args) { 4 | Scanner sc = new Scanner(System.in); 5 | System.out.println("Enter the number of Rows for Pattern: "); 6 | int i,j,k,n,asci; 7 | n = sc.nextInt(); 8 | int countSpace=n-1; 9 | for(i=1;i<=n;i++) { 10 | for(j=0;j0;k--) 18 | System.out.print(k); 19 | } 20 | else { 21 | if(i%3==0) 22 | asci = 96; 23 | else 24 | asci = 64; 25 | for(k=1;k<=i;k++) 26 | System.out.print((char)(k+asci)); 27 | for(k=i-1;k>0;k--) 28 | System.out.print((char)(k+asci)); 29 | } 30 | System.out.println(); 31 | 32 | } 33 | 34 | } 35 | } 36 | /* 37 | Output: 38 | Enter the number of Rows for Pattern: 7 39 | 40 | A 41 | ABA 42 | 12321 43 | ABCDCBA 44 | ABCDEDCBA 45 | 12345654321 46 | ABCDEFGFEDCBA 47 | 48 | */ -------------------------------------------------------------------------------- /PatternPrograms/W_alphabet.py: -------------------------------------------------------------------------------- 1 | #Pyhton program to create a Pattern of 'W' Alphabet 2 | 3 | i,j=0,3 # spaces these digits will be used for altering number of rows/columns and needs to be changes as per requirements 4 | 5 | #iteration for rows 6 | for r in range(4): 7 | #iteration for columns 8 | for c in range(7): 9 | #here we are placing stars on either sides and inner diagonal of 'W' 10 | if c==0 or c==6 or (c==5 and r==2) or c==4 and r==1: 11 | print('*',end='') 12 | elif r==i and c==j: 13 | #places stars at DIAGONALS 14 | print('*',end='') 15 | i+=1 16 | j-=1 17 | else: 18 | print(end=' ') 19 | print() 20 | -------------------------------------------------------------------------------- /PatternPrograms/indiaMap_pattern.java: -------------------------------------------------------------------------------- 1 | public class indiaMap_pattern{ 2 | public static void main(String[] arr){ 3 | int a=10,b=0,c=10; 4 | String s1 ="TFy!QJu ROo TNn(ROo)SLq SLq ULo+UHs UJq TNn*RPn/QPbEWS_JSWQAIJO^NBELPeHBFHT}TnALVlBLOFAkHFOuFETpHCStHAUFAgcEAelclcn^r^r\\tZvYxXyT|S~Pn SPm SOn TNn ULo0ULo#ULo-WHq!WFs XDt!"; 5 | a=s1.charAt(b); 6 | while(a!=0){ 7 | if(b<170){ 8 | a=s1.charAt(b); 9 | b++; 10 | while(a-- >64){ 11 | 12 | if(++c=='Z'){ 13 | c/=9; 14 | System.out.println((char)(c)); 15 | } 16 | else{ 17 | System.out.print((char)(33^(b & 0x01))); 18 | } 19 | } 20 | 21 | } 22 | else 23 | break; 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /PatternPrograms/numberpyramid.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class ritikakatoch { 3 | public static void main(String[] args) { 4 | Scanner inr = new Scanner(System.in); 5 | int n = inr.nextInt(); 6 | int k = 1; 7 | for(int i = 1; i <= n; ++i, k = 1) { 8 | for(int space = 1; space <= n-i; ++space) { 9 | System.out.print(" "); 10 | } 11 | while(k <= 2 * i - 1) { 12 | System.out.print(k+" "); 13 | ++k; 14 | } 15 | System.out.println(); 16 | } 17 | 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /PatternPrograms/pattern.java: -------------------------------------------------------------------------------- 1 | package com.practice; 2 | 3 | class buubleSort { 4 | public static void main(String[] args) { 5 | 6 | System.out.println("Increasing star pattern "); 7 | for (int i = 1; i <= 5; i++ ) { 8 | for (int j = 1; j <= i; j++) { 9 | System.out.print("* "); 10 | } 11 | System.out.println(); 12 | } 13 | 14 | System.out.println(); 15 | 16 | System.out.println("Decreasing star pattern "); 17 | for (int i = 1; i <= 5; i++ ) { 18 | for (int j = i; j < 5; j++) { 19 | System.out.print("* "); 20 | } 21 | System.out.println(); 22 | } 23 | 24 | 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /PatternPrograms/pattern_of_alphabets.py: -------------------------------------------------------------------------------- 1 | # Python code 3.x to demonstrate star pattern 2 | 3 | # Function to demonstrate printing pattern of alphabets 4 | def contalpha(n): 5 | 6 | # initializing value corresponding to 'A' 7 | # ASCII value 8 | num = 65 9 | 10 | # outer loop to handle number of rows 11 | - for i in range(0, n): 12 | 13 | # inner loop to handle number of columns 14 | # values changing acc. to outer loop 15 | for j in range(0, i+1): 16 | 17 | # explicitely converting to char 18 | ch = chr(num) 19 | 20 | # printing char value 21 | print(ch, end=" ") 22 | 23 | # incrementing at each column 24 | num = num +1 25 | 26 | 27 | # ending line after each row 28 | print("\r") 29 | 30 | # Driver code 31 | n = 5 32 | contalpha(n) 33 | -------------------------------------------------------------------------------- /PatternPrograms/pyramid.py: -------------------------------------------------------------------------------- 1 | def triangle(n): 2 | 3 | k = n - 1 4 | 5 | for i in range(0, n): 6 | 7 | for j in range(0, k): 8 | print(end=" ") 9 | 10 | k = k - 1 11 | 12 | for j in range(0, i+1): 13 | 14 | print("* ", end="") 15 | 16 | print("\r") 17 | 18 | n = 5 19 | triangle(n) 20 | -------------------------------------------------------------------------------- /PatternPrograms/rectangle_pattern.c: -------------------------------------------------------------------------------- 1 | //Rectangle pattern program in c : program asks the user to enter length and breadth of the hollow rectangle they want to create. 2 | //Srishti Arya 3 | 4 | #include 5 | 6 | void print_rectangle(int n, int m ) 7 | { 8 | int i, j; 9 | for (i = 1; i <= n; i++) 10 | { 11 | for (j = 1; j <= m ; j++) 12 | { 13 | if (i==1 || i==n || j==1 || j==m ) 14 | printf("*"); 15 | else 16 | printf(" "); 17 | } 18 | printf("\n"); 19 | } 20 | 21 | } 22 | 23 | int main() 24 | { 25 | int columns,rows; 26 | printf("Enter length and breadth of a rectangle: "); 27 | scanf("%d %d",&rows,&columns); 28 | print_rectangle(rows, columns); 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /PatternPrograms/squarepattern.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int main() 4 | { 5 | int i, j, N; 6 | 7 | /* Input number of rows from user */ 8 | printf("Enter number of rows: "); 9 | scanf("%d", &N); 10 | 11 | /* Iterate through N rows */ 12 | for(i=1; i<=N; i++) 13 | { 14 | /* Iterate over columns */ 15 | for(j=1; j<=N; j++) 16 | { 17 | /* Print star for each column */ 18 | printf("*"); 19 | } 20 | 21 | /* Move to the next line/row */ 22 | printf("\n"); 23 | } 24 | 25 | return 0; 26 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # HacktoberFest Repository (🌟 Star this repository!🌟) 4 | This is a Hacktoberfest-Repository,feel free to make your conttributions here this month to win your swagss!!Happy Coding! :) 5 | 6 | ## 💡 What is Hacktoberfest? 7 | A month-long celebration from October 1st - 31st sponsored by Digital Ocean and GitHub to get people involved in Open Source. Create your very first pull request to any public repository on GitHub and contribute to the open source developer community. 8 | 9 | 👉 Official HacktoberFest Page 👈 10 | 11 | ## 👕 HacktoberFest- Get your Free T-shirt Now. 12 | Create your first Pull Request 🔥(PR). 13 | 14 | ### 👣 Steps to Make your 1st PR Contribution: 15 | 1) Fork this repository by clicking the Fork button in the top right of this page. 16 | 2) Click on Add File button and select Create new file button in your personal copy of this repository. 17 | 1) Set the file name with (FileName).java (FileName).py or (FileName).c or (FileName).cpp or (FileName).cs or (FileName).kt or (FileName).js 18 | 2) Then write your code and hit commit. 19 | 3) Then click on pull request tab. Refer guidelines. 20 | 4) Generate a new Pull Request and Make the contribution. 21 | 5) Happy Coding! :) 22 | 23 | -------------------------------------------------------------------------------- /Recursion/ArmstrongNumber.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | //ARMSTRONG number means sum of numbers of cubes equal to the number 3 | public class ArmstrongNumber { 4 | public static void main(String[] args) { 5 | Scanner scanner = new Scanner(System.in); 6 | System.out.println("Enter any Number?=>"); 7 | // taking input from the user 8 | int input = scanner.nextInt(); 9 | //calling isArmstrongNumber() method and put in a variable 10 | double checkNumber=isArmstrongNumber(input); 11 | //checking the number 12 | if(input==checkNumber) 13 | { 14 | System.out.println(input+" is ARMSTRONG NUMBER"); 15 | } 16 | else 17 | { 18 | System.out.println(input+" not is ARMSTRONG NUMBER"); 19 | } 20 | scanner.close(); 21 | } 22 | static int remainderNumber; 23 | static double total = 0; 24 | public static double isArmstrongNumber(int inputNumber) { 25 | if (inputNumber > 0) { 26 | remainderNumber = inputNumber % 10;//separating digits 27 | total = total + Math.pow(remainderNumber, 3);//cubes sum 28 | isArmstrongNumber(inputNumber / 10);//recursive call 29 | } 30 | return total; 31 | } 32 | } -------------------------------------------------------------------------------- /Recursion/Binary_Exponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int binExpRec(int a, int b){ 5 | 6 | if(b==0){ 7 | return 1; 8 | } 9 | 10 | long long r = binExpRec(a,b/2); 11 | 12 | if(b & 1){ 13 | return (a * r * r); 14 | } 15 | else{ 16 | return r * r; 17 | } 18 | 19 | } 20 | 21 | int main(){ 22 | int a,b; 23 | 24 | cout<<"Enter the number and its power: "; 25 | cin>>a>>b; 26 | 27 | int finalAns = binExpRec(a,b); 28 | cout<< a << " to the power " << b << " = " << finalAns; 29 | 30 | return 0; 31 | } 32 | -------------------------------------------------------------------------------- /Recursion/CombinationsInAStringOfDigits.java: -------------------------------------------------------------------------------- 1 | // Java program to find all combinations 2 | // of numbers from a given string of digits 3 | class Main { 4 | 5 | // function to print combinations of numbers 6 | // in given input string 7 | static void printCombinations(char[] input, 8 | int index, 9 | char[] output, 10 | int outLength) 11 | { 12 | // no more digits left in input string 13 | if (input.length == index) 14 | { 15 | // print output string & return 16 | System.out.println(String.valueOf(output)); 17 | return; 18 | } 19 | 20 | // place current digit in input string 21 | output[outLength] = input[index]; 22 | 23 | // separate next digit with a space 24 | output[outLength + 1] = ' '; 25 | 26 | printCombinations(input, index + 1, output, 27 | outLength + 2); 28 | 29 | // if next digit exists make a 30 | // call without including space 31 | if(input.length!=index + 1) 32 | printCombinations(input, index + 1, output, 33 | outLength + 1); 34 | } 35 | 36 | // Driver Code 37 | public static void main(String[] args) 38 | { 39 | char input[] = "1214".toCharArray(); 40 | char []output = new char[100]; 41 | 42 | printCombinations(input, 0, output, 0); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /Recursion/Factorial_Rec.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Factorial function 5 | int f(int n) 6 | { 7 | // Stop condition 8 | if (n == 0 || n == 1) 9 | return 1; 10 | else 11 | return n * f(n - 1); 12 | } 13 | 14 | // Driver code 15 | int main() 16 | { 17 | int n = 5; 18 | cout<<"factorial of "< 0) 24 | { 25 | for (int i = 0; i < length; i++) 26 | { 27 | Console.Write($"{FibonacciSeries(i)} "); 28 | } 29 | } 30 | else 31 | { 32 | Console.WriteLine($"You entered a wrong input: {length}"); 33 | } 34 | } 35 | } -------------------------------------------------------------------------------- /Recursion/FibonacciI_recusrion.c: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int Fibonacci(int); 4 | 5 | int main() 6 | { 7 | int n, i = 0, c; 8 | 9 | scanf("%d",&n); 10 | 11 | printf("Fibonacci series\n"); 12 | 13 | for ( c = 1 ; c <= n ; c++ ) 14 | { 15 | printf("%d\n", Fibonacci(i)); 16 | i++; 17 | } 18 | 19 | return 0; 20 | } 21 | 22 | int Fibonacci(int n) 23 | { 24 | if ( n == 0 ) 25 | return 0; 26 | else if ( n == 1 ) 27 | return 1; 28 | else 29 | return ( Fibonacci(n-1) + Fibonacci(n-2) ); 30 | } 31 | -------------------------------------------------------------------------------- /Recursion/Fibonacci_Rec.java: -------------------------------------------------------------------------------- 1 | //Fibonacci Series using Recursion 2 | class Fibonacci_Rec 3 | { 4 | static int fib(int n) 5 | { 6 | if (n <= 1) 7 | return n; 8 | return fib(n-1) + fib(n-2); 9 | } 10 | 11 | public static void main (String args[]) 12 | { 13 | int n = 9; 14 | System.out.println(fib(n)); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Recursion/Fibonacci_recursive.py: -------------------------------------------------------------------------------- 1 | #---Fibonacci recursive python function--- 2 | def Fibonacci(n): 3 | if n<=1 : 4 | return n 5 | else : 6 | #recursive function 7 | return Fibonacci(n-1)+Fibonacci(n-2) 8 | 9 | 10 | #---main--- 11 | n = int(input("Input an integer: ")) #get the number 12 | 13 | while n!=-1: #checking if input value is not equal to -1 14 | #if input is not equals to -1 15 | Fibonacci(n) #pass it to the function 16 | print("Output is",Fibonacci(n)) 17 | #asking user to input another integer value 18 | n = int(input("Input an integer: ")) #get the number 19 | -------------------------------------------------------------------------------- /Recursion/GCD_Rec.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to find GCD of two numbers 2 | #include 3 | using namespace std; 4 | // Recursive function to return gcd of a and b 5 | int gcd(int a, int b) 6 | { 7 | // Everything divides 0 8 | if (a == 0) 9 | return b; 10 | if (b == 0) 11 | return a; 12 | 13 | // base case 14 | if (a == b) 15 | return a; 16 | 17 | // a is greater 18 | if (a > b) 19 | return gcd(a-b, b); 20 | return gcd(a, b-a); 21 | } 22 | 23 | // Driver program to test above function 24 | int main() 25 | { 26 | int a = 98, b = 56; 27 | cout<<"GCD of "< b) 19 | return gcd(a-b, b); 20 | return gcd(a, b-a); 21 | } 22 | 23 | // Driver method 24 | public static void main(String[] args) 25 | { 26 | int a = 98, b = 56; 27 | System.out.println("GCD of " + a +" and " + b + " is " + gcd(a, b)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Recursion/LeafNodesInBinaryTree.java: -------------------------------------------------------------------------------- 1 | // Java program to print leaf nodes 2 | // from left to right 3 | import java.util.*; 4 | 5 | class Main { 6 | 7 | // A Binary Tree Node 8 | static class Node 9 | { 10 | public int data; 11 | public Node left, right; 12 | }; 13 | 14 | // Function to print leaf 15 | // nodes from left to right 16 | static void printLeafNodes(Node root) 17 | { 18 | 19 | // If node is null, return 20 | if (root == null) 21 | return; 22 | 23 | // If node is leaf node, print its data 24 | if (root.left == null && 25 | root.right == null) 26 | { 27 | System.out.print(root.data + " "); 28 | return; 29 | } 30 | 31 | // If left child exists, check for leaf 32 | // recursively 33 | if (root.left != null) 34 | printLeafNodes(root.left); 35 | 36 | // If right child exists, check for leaf 37 | // recursively 38 | if (root.right != null) 39 | printLeafNodes(root.right); 40 | } 41 | 42 | // Utility function to create a new tree node 43 | static Node newNode(int data) 44 | { 45 | Node temp = new Node(); 46 | temp.data = data; 47 | temp.left = null; 48 | temp.right = null; 49 | return temp; 50 | } 51 | 52 | // Driver code 53 | public static void main(String []args) 54 | { 55 | 56 | // Let us create binary tree shown in 57 | // above diagram 58 | Node root = newNode(1); 59 | root.left = newNode(2); 60 | root.right = newNode(3); 61 | root.left.left = newNode(4); 62 | root.right.left = newNode(5); 63 | root.right.right = newNode(8); 64 | root.right.left.left = newNode(6); 65 | root.right.left.right = newNode(7); 66 | root.right.right.left = newNode(9); 67 | root.right.right.right = newNode(10); 68 | 69 | // Print leaf nodes of the given tree 70 | printLeafNodes(root); 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Recursion/Predict-the-Winner.java: -------------------------------------------------------------------------------- 1 | 2 | 3 | public class Solution { 4 | public boolean PredictTheWinner(int[] nums) { 5 | Integer[][] memo = new Integer[nums.length][nums.length]; 6 | return winner(nums, 0, nums.length - 1, memo) >= 0; 7 | } 8 | public int winner(int[] nums, int s, int e, Integer[][] memo) { 9 | if (s == e) 10 | return nums[s]; 11 | if (memo[s][e] != null) 12 | return memo[s][e]; 13 | int a = nums[s] - winner(nums, s + 1, e, memo); 14 | int b = nums[e] - winner(nums, s, e - 1, memo); 15 | memo[s][e] = Math.max(a, b); 16 | return memo[s][e]; 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Recursion/Reverse-String.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | public class Rev 3 | { 4 | static String str=""; 5 | public static String reverse(String st,int i) 6 | { 7 | if(i<0) 8 | return ""; 9 | else 10 | { 11 | str=str+st.charAt(i); 12 | reverse(st,i-1); 13 | return str; 14 | } 15 | } 16 | public static void main(String args[]) 17 | { 18 | Scanner in = new Scanner(System.in); 19 | String s=in.next(); 20 | System.out.println(reverse(s,s.length()-1)); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /Recursion/Tower of Hanoi.java: -------------------------------------------------------------------------------- 1 | // Java recursive program to solve tower of hanoi puzzle 2 | 3 | class GFG 4 | { 5 | // Java recursive function to solve tower of hanoi puzzle 6 | static void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod) 7 | { 8 | if (n == 1) 9 | { 10 | System.out.println("Move disk 1 from rod " + from_rod + " to rod " + to_rod); 11 | return; 12 | } 13 | towerOfHanoi(n-1, from_rod, aux_rod, to_rod); 14 | System.out.println("Move disk " + n + " from rod " + from_rod + " to rod " + to_rod); 15 | towerOfHanoi(n-1, aux_rod, to_rod, from_rod); 16 | } 17 | 18 | // Driver method 19 | public static void main(String args[]) 20 | { 21 | int n = 4; // Number of disks 22 | towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Recursion/Tower of Hanoi.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | function stepsToSolveHanoiT(height, srcP, desP, bufferP) { 4 | if (height >= 1) { 5 | 6 | // Move a tower of height-1 to the buffer peg, using the destination peg. 7 | stepsToSolveHanoiT(height - 1, srcP, bufferP, desP); 8 | 9 | // Move the remaining disk to the destination peg. 10 | console.log('Move disk from Tower ', srcP, ' to Tower ', desP); 11 | 12 | // Move the tower of `height-1` from the `buffer peg` to the `destination peg` using the `source peg`. 13 | stepsToSolveHanoiT(height - 1, bufferP, desP, srcP); 14 | } 15 | 16 | return; 17 | } 18 | 19 | stepsToSolveHanoiT(3, "A", "C", "B"); 20 | 21 | // Move disk from Tower A to Tower C 22 | // Move disk from Tower A to Tower B 23 | // Move disk from Tower C to Tower B 24 | // Move disk from Tower A to Tower C 25 | // Move disk from Tower B to Tower A 26 | // Move disk from Tower B to Tower C 27 | // Move disk from Tower A to Tower C 28 | -------------------------------------------------------------------------------- /Recursion/TowerOfHanoi.py: -------------------------------------------------------------------------------- 1 | def TowerOfHanoi(n , source, destination, auxiliary): 2 | if n==1: 3 | print "Move disk 1 from source",source,"to destination",destination 4 | return 5 | TowerOfHanoi(n-1, source, auxiliary, destination) 6 | print "Move disk",n,"from source",source,"to destination",destination 7 | TowerOfHanoi(n-1, auxiliary, destination, source) 8 | 9 | # Driver code 10 | n = 4 11 | TowerOfHanoi(n,'A','B','C') 12 | # A, C, B are the name of rods 13 | -------------------------------------------------------------------------------- /Recursion/binomial_coefiicient.py: -------------------------------------------------------------------------------- 1 | # A recursive code for calculating the Binomial Coefficient in Python 2 | 3 | 4 | def binomialCoeff(n, k): 5 | 6 | if k > n: 7 | return 0 8 | if k == 0 or k == n: 9 | return 1 10 | 11 | # Recursive Call 12 | return binomialCoeff(n-1, k-1) + binomialCoeff(n-1, k) 13 | 14 | 15 | # Driver Program to test ht above function 16 | n = 5 17 | k = 2 18 | print "Value of C(%d,%d) is (%d)" % (n, k, 19 | binomialCoeff(n, k)) 20 | -------------------------------------------------------------------------------- /Recursion/josephus.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/shecoderfinally/Sorting-and-Searching-Techniques/b4a825f6a91d8aeed3ed86bfd14a039c2a633de6/Recursion/josephus.java -------------------------------------------------------------------------------- /Recursion/string_reverse_using_recursion.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void reverse(string &str) 5 | { 6 | stack st; 7 | for (int i=0; i= left) 8 | { 9 | int mid = left + (right - left) / 2; 10 | 11 | if (elements[mid] == x) // the element is in the middle of the array 12 | return mid; 13 | 14 | if (elements[mid] > x) // the element must be in the left subarray 15 | { 16 | return BinarySearch(elements, left, mid - 1, x); 17 | } 18 | 19 | return BinarySearch(elements, mid + 1, right, x); // the element must be in the right subarray 20 | } 21 | 22 | return -1; // if the element is not present in the array, we return -1 23 | } 24 | 25 | public static void Main() 26 | { 27 | int[] elements = { 0, 10, 50, 89, 100, 270 }; 28 | int lentgh = elements.Length; 29 | int x = 20; 30 | int position = BinarySearch(elements, 0, lentgh - 1, x); 31 | 32 | if (position == -1) 33 | { 34 | Console.WriteLine($"Element {x} not found in array."); 35 | } 36 | else 37 | { 38 | Console.WriteLine($"Element {x} found at position: {position}"); 39 | } 40 | } 41 | } -------------------------------------------------------------------------------- /Searching/Binary Search/BinarySearch.java: -------------------------------------------------------------------------------- 1 | 2 | // Java implementation of recursive Binary Search 3 | class BinarySearch { 4 | // Returns index of x if it is present in arr[l.. 5 | // r], else return -1 6 | int binarySearch(int arr[], int l, int r, int x) 7 | { 8 | if (r >= l) { 9 | int mid = l + (r - l) / 2; 10 | 11 | // If the element is present at the 12 | // middle itself 13 | if (arr[mid] == x) 14 | return mid; 15 | 16 | // If element is smaller than mid, then 17 | // it can only be present in left subarray 18 | if (arr[mid] > x) 19 | return binarySearch(arr, l, mid - 1, x); 20 | 21 | // Else the element can only be present 22 | // in right subarray 23 | return binarySearch(arr, mid + 1, r, x); 24 | } 25 | 26 | // We reach here when element is not present 27 | // in array 28 | return -1; 29 | } 30 | 31 | // Driver method to test above 32 | public static void main(String args[]) 33 | { 34 | BinarySearch ob = new BinarySearch(); 35 | int arr[] = { 2, 3, 4, 10, 40 }; 36 | int n = arr.length; 37 | int x = 10; 38 | int result = ob.binarySearch(arr, 0, n - 1, x); 39 | if (result == -1) 40 | System.out.println("Element not present"); 41 | else 42 | System.out.println("Element found at index " + result); 43 | } 44 | } 45 | /* This code is contributed by Rajat Mishra */ 46 | -------------------------------------------------------------------------------- /Searching/Binary Search/BinarySearch.kt: -------------------------------------------------------------------------------- 1 | fun main(args: Array) { 2 | val input = readLine()!!.trim().split(" ").map { it -> it.toInt() }.toIntArray() // to read an array (from user input) 3 | val eleToSearch = readLine()!!.trim().toInt() // to read the element to be searched (from user input) 4 | val pos = binarySearchIterative(input, eleToSearch) 5 | if(pos >= 0 ) { 6 | println(pos) // to print position at last 7 | } else { 8 | println("Position not found") 9 | } 10 | } 11 | 12 | fun binarySearchIterative(input: IntArray, eleToSearch: Int) : Int{ 13 | var low = 0 14 | var high = input.size–1 15 | var mid:Int 16 | while(low <= high) { 17 | mid = low + ((high – low) / 2) 18 | when { 19 | eleToSearch >input[mid] -> low = mid+1 // element is greater than middle element of array, so it will be in right half of array 20 | eleToSearch == input[mid] -> return mid // found the element 21 | eleToSearch < input[mid] -> high = mid–1 //element is less than middle element of array, so it will be in left half of the array. 22 | } 23 | } 24 | return –1 25 | } 26 | -------------------------------------------------------------------------------- /Searching/Binary Search/BinarySearch.py: -------------------------------------------------------------------------------- 1 | def binary_search(arr, x): 2 | low = 0 3 | high = len(arr) - 1 4 | mid = 0 5 | 6 | while low <= high: 7 | 8 | mid = (high + low) // 2 9 | 10 | if arr[mid] < x: 11 | low = mid + 1 12 | 13 | elif arr[mid] > x: 14 | high = mid - 1 15 | 16 | else: 17 | return mid 18 | 19 | return -1 20 | 21 | # result = binary_search(arr, x) 22 | 23 | # if result != -1: 24 | # print("Element is present at index", str(result)) 25 | # else: 26 | # print("Element is not present in array") 27 | -------------------------------------------------------------------------------- /Searching/Binary Search/Binary_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i, low, high, mid, n, key, array[100]; 5 | printf("Enter number of elements:"); 6 | scanf("%d",&n); 7 | printf("Enter %d integers:", n); 8 | for(i = 0; i < n; i++) 9 | scanf("%d",&array[i]); 10 | printf("Enter value to find:"); 11 | scanf("%d", &key); 12 | low = 0; 13 | high = n - 1; 14 | mid = (low+high)/2; 15 | while (low <= high) { 16 | if(array[mid] < key) 17 | low = mid + 1; 18 | else if (array[mid] == key) { 19 | printf("%d found at location %d", key, mid+1); 20 | break; 21 | } 22 | else 23 | high = mid - 1; 24 | mid = (low + high)/2; 25 | } 26 | if(low > high) 27 | printf("Not found! %d isn't present in the list", key); 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Searching/Binary Search/Order Agnostic Binary Search.java: -------------------------------------------------------------------------------- 1 | // Given a key and an array whose order of sorting is not known. Find the position of the key using binary search. 2 | public class Main{ 3 | static int bsearch(int arr[],int key){ 4 | int start=0; 5 | int end=arr.length-1; 6 | boolean isasscending; 7 | if(arr[start] arr[mid]) 24 | end=mid-1; 25 | else 26 | start=mid+1; 27 | } 28 | } 29 | return -1; 30 | } 31 | public static void main(String[] args) { 32 | int[] arr={1926,2756,3581,4386,5145}; 33 | int key=4386; 34 | System.out.println(bsearch(arr,key)); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Searching/Binary Search/binary_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int i, arr[10], num, first, last, middle; 6 | cout<<"Enter 10 Elements (in ascending order): "; 7 | for(i=0; i<10; i++) 8 | cin>>arr[i]; 9 | cout<<"\nEnter Element to be Search: "; 10 | cin>>num; 11 | first = 0; 12 | last = 9; 13 | middle = (first+last)/2; 14 | while(first <= last) 15 | { 16 | if(arr[middle]last) 28 | cout<<"\nThe number, "< arr = [0, 1, 3, 4, 5, 8, 9, 22]; 3 | int userValue = 3; 4 | int min = 0; 5 | int max = arr.length - 1; 6 | binarySearch(arr, userValue, min, max); 7 | } 8 | 9 | binarySearch(List arr, int userValue, int min, int max) { 10 | if (max >= min) { 11 | print('min $min'); 12 | print('max $max'); 13 | int mid = ((max + min) / 2).floor(); 14 | if (userValue == arr[mid]) { 15 | print('your item is at index: ${mid}'); 16 | } else if (userValue > arr[mid]) { 17 | binarySearch(arr, userValue, mid + 1, max); 18 | } else { 19 | binarySearch(arr, userValue, min, mid - 1); 20 | } 21 | } 22 | return null; 23 | } 24 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int jumpSearch(int arr[], int x, int n) 5 | { 6 | int step = sqrt(n); 7 | 8 | int prev = 0; 9 | while (arr[min(step, n)-1] < x) 10 | { 11 | prev = step; 12 | step += sqrt(n); 13 | if (prev >= n) 14 | return -1; 15 | } 16 | 17 | while (arr[prev] < x) 18 | { 19 | prev++; 20 | 21 | if (prev == min(step, n)) 22 | return -1; 23 | } 24 | if (arr[prev] == x) 25 | return prev; 26 | 27 | return -1; 28 | } 29 | 30 | int main() 31 | { 32 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 33 | 34, 55, 89, 144, 233, 377, 610 }; 34 | int x = 55; 35 | int n = sizeof(arr) / sizeof(arr[0]); 36 | 37 | int index = jumpSearch(arr, x, n); 38 | 39 | cout << "\nNumber " << x << " is at index " << index; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | public class Program 4 | { 5 | public static int JumpSearch(int[] elements, int x) 6 | { 7 | // array lentgh 8 | int length = elements.Length; 9 | 10 | // finding the jump step 11 | int step = (int)Math.Floor(Math.Sqrt(length)); 12 | int prev = 0; 13 | 14 | while (elements[Math.Min(step, length) - 1] < x) 15 | { 16 | prev = step; 17 | step += (int)Math.Floor(Math.Sqrt(length)); 18 | 19 | if (prev >= length) 20 | { 21 | return -1; 22 | } 23 | } 24 | 25 | while (elements[prev] < x) 26 | { 27 | prev++; 28 | 29 | if (prev == Math.Min(step, length)) 30 | { 31 | return -1; 32 | } 33 | } 34 | 35 | // if element is found 36 | if (elements[prev] == x) 37 | { 38 | return prev; 39 | } 40 | 41 | return -1; 42 | } 43 | 44 | public static void Main() 45 | { 46 | // sorted array 47 | int[] elements = { 5, 12, 22, 41, 55, 57, 60, 74, 91 }; 48 | int x = 22; 49 | int position = JumpSearch(elements, x); 50 | 51 | if (position == -1) 52 | { 53 | Console.Write($"Number {x} not found in the array"); 54 | } 55 | else 56 | { 57 | Console.Write($"Number {x} is at position/index: {position}"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.java: -------------------------------------------------------------------------------- 1 | public class JumpSearch 2 | { 3 | public static int jumpSearch(int[] arr, int x) 4 | { 5 | int n = arr.length; 6 | 7 | 8 | int step = (int)Math.floor(Math.sqrt(n)); 9 | 10 | 11 | int prev = 0; 12 | while (arr[Math.min(step, n)-1] < x) 13 | { 14 | prev = step; 15 | step += (int)Math.floor(Math.sqrt(n)); 16 | if (prev >= n) 17 | return -1; 18 | } 19 | 20 | 21 | while (arr[prev] < x) 22 | { 23 | prev++; 24 | 25 | 26 | if (prev == Math.min(step, n)) 27 | return -1; 28 | } 29 | 30 | 31 | if (arr[prev] == x) 32 | return prev; 33 | 34 | return -1; 35 | } 36 | 37 | 38 | public static void main(String [ ] args) 39 | { 40 | int arr[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 41 | 34, 55, 89, 144, 233, 377, 610}; 42 | int x = 55; 43 | 44 | 45 | int index = jumpSearch(arr, x); 46 | 47 | 48 | System.out.println("\nNumber " + x + 49 | " is at index " + index); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /Searching/Jump Search/JumpSearch.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | def jumpSearch( arr , x , n ): 4 | 5 | 6 | step = math.sqrt(n) 7 | 8 | 9 | prev = 0 10 | while arr[int(min(step, n)-1)] < x: 11 | prev = step 12 | step += math.sqrt(n) 13 | if prev >= n: 14 | return -1 15 | 16 | 17 | while arr[int(prev)] < x: 18 | prev += 1 19 | 20 | 21 | if prev == min(step, n): 22 | return -1 23 | 24 | 25 | if arr[int(prev)] == x: 26 | return prev 27 | 28 | return -1 29 | 30 | 31 | arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 32 | 34, 55, 89, 144, 233, 377, 610 ] 33 | x = 55 34 | n = len(arr) 35 | 36 | 37 | index = jumpSearch(arr, x, n) 38 | 39 | 40 | print("Number" , x, "is at index" ,"%.0f"%index) 41 | -------------------------------------------------------------------------------- /Searching/Linear Search/Linear Search.kt: -------------------------------------------------------------------------------- 1 | fun linearSearch(list:List, key:Any):Int?{ 2 | for ((index, value) in list.withIndex()) { 3 | if (value == key){ 4 | return index 5 | } 6 | } 7 | return null 8 | } 9 | fun main(args: Array) { 10 | println(" 11 | Ordered list:") 12 | val someList = listOf(9, 7, "Adam", "Clark", "John", "Tim", "Zack", 6) 13 | println(someList) 14 | val name = 7 15 | val position = linearSearch(someList, name) 16 | println("${name} is in the position ${position} in the ordered List. 17 | ") 18 | 19 | val name2 = "Tim" 20 | val position2 = linearSearch(someList, name2) 21 | println("${name2} is in the position ${position2} in the ordered List. 22 | ") 23 | } 24 | -------------------------------------------------------------------------------- /Searching/Linear Search/Linear search.py: -------------------------------------------------------------------------------- 1 | def search(arr, x): 2 | 3 | for i in range(len(arr)): 4 | 5 | if arr[i] == x: 6 | return i 7 | 8 | return -1 9 | -------------------------------------------------------------------------------- /Searching/Linear Search/LinearSearch.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | class Program 4 | { 5 | public static int LinearSearch(int[] elements, int x) 6 | { 7 | var n = elements.Length; 8 | 9 | for (int i = 0; i < n; i++) 10 | { 11 | // if the element is found, we return the position/index 12 | if (elements[i] == x) 13 | { 14 | return i; 15 | } 16 | } 17 | 18 | // if the element is not found, we return -1 19 | return -1; 20 | } 21 | 22 | public static void Main() 23 | { 24 | int[] elements = { 10, 2, 5, 38, 100, 28 }; 25 | var x = 10; 26 | var position = LinearSearch(elements, x); 27 | 28 | if (position == -1) 29 | { 30 | Console.WriteLine("Element was not found in the specified array"); 31 | } 32 | else 33 | { 34 | Console.WriteLine($"Element found at position {position}"); 35 | } 36 | } 37 | } -------------------------------------------------------------------------------- /Searching/Linear Search/Linear_search.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int array[100], search, c, n; 5 | 6 | printf("Enter number of elements in array\n"); 7 | scanf("%d", &n); 8 | 9 | printf("Enter %d integer(s)\n", n); 10 | 11 | for (c = 0; c < n; c++) 12 | scanf("%d", &array[c]); 13 | 14 | printf("Enter a number to search\n"); 15 | scanf("%d", &search); 16 | 17 | for (c = 0; c < n; c++) 18 | { 19 | if (array[c] == search) /* If required element is found */ 20 | { 21 | printf("%d is present at location %d.\n", search, c+1); 22 | break; 23 | } 24 | } 25 | if (c == n) 26 | printf("%d isn't present in the array.\n", search); 27 | 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /Searching/Linear Search/linearsearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int n,key; 6 | bool found=false; 7 | cout<<"Enter the size of array and key\n"; 8 | cin>>n>>key; 9 | int arr[n]; 10 | cout<<"Enter the elements:\n"; 11 | for(int i=0;i>arr[i]; 14 | } 15 | for(int i=0;i 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/BubbleSort.c: -------------------------------------------------------------------------------- 1 | //Bubble Sort in C 2 | #include 3 | 4 | int main() 5 | { 6 | int array[100], n, c, d, swap; 7 | 8 | printf("Enter number of elements\n"); 9 | scanf("%d", &n); 10 | 11 | printf("Enter %d integers\n", n); 12 | 13 | for (c = 0; c < n; c++) 14 | scanf("%d", &array[c]); 15 | 16 | for (c = 0 ; c < n - 1; c++) 17 | { 18 | for (d = 0 ; d < n - c - 1; d++) 19 | { 20 | if (array[d] > array[d+1]) /* For decreasing order use '<' instead of '>' */ 21 | { 22 | swap = array[d]; 23 | array[d] = array[d+1]; 24 | array[d+1] = swap; 25 | } 26 | } 27 | } 28 | 29 | printf("Sorted list in ascending order:\n"); 30 | 31 | for (c = 0; c < n; c++) 32 | printf("%d\n", array[c]); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/BubbleSort.java: -------------------------------------------------------------------------------- 1 | 2 | // Java program for implementation of Bubble Sort 3 | class BubbleSort 4 | { 5 | void bubbleSort(int arr[]) 6 | { 7 | int n = arr.length; 8 | for (int i = 0; i < n-1; i++) 9 | for (int j = 0; j < n-i-1; j++) 10 | if (arr[j] > arr[j+1]) 11 | { 12 | // swap arr[j+1] and arr[j] 13 | int temp = arr[j]; 14 | arr[j] = arr[j+1]; 15 | arr[j+1] = temp; 16 | } 17 | } 18 | 19 | /* Prints the array */ 20 | void printArray(int arr[]) 21 | { 22 | int n = arr.length; 23 | for (int i=0; i { 2 | if(!Array.isArray(nums)) return -1; // --->if passed argument is not array 3 | if(nums.length<2) return nums; // --->if array length is one or less 4 | 5 | let swapped=false 6 | temp=0, 7 | count=-1, 8 | arrLength=0; 9 | 10 | 11 | do{ 12 | count ++; 13 | swapped=false; 14 | arrLength = (nums.length-1) - count; //---> not loop through sorted items 15 | for(let i=0; i<=arrLength; i++){ 16 | if(nums[i]>nums[i+1]){ 17 | temp=nums[i+1]; 18 | nums[i+1]=nums[i]; 19 | nums[i]=temp; 20 | swapped=true; 21 | } 22 | } 23 | } 24 | 25 | while(swapped) 26 | return nums; 27 | } 28 | console.log(bubble_Sort([3, 0, 2, 5, -1, 4, 1])); 29 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/BubbleSort.php: -------------------------------------------------------------------------------- 1 | $numlist[$i + 1] ) 16 | { 17 | list( $numlist[$i + 1], $numlist[$i] ) = 18 | array( $numlist[$i], $numlist[$i + 1] ); 19 | $swap = true; 20 | } 21 | } 22 | } 23 | while( $swap ); 24 | 25 | return $numlist; 26 | 27 | } 28 | ?> 29 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Bubblesort.cpp: -------------------------------------------------------------------------------- 1 | // Optimized implementation of Bubble sort 2 | #include 3 | using namespace std; 4 | void swap(int *xp, int *yp) 5 | { 6 | int temp = *xp; 7 | *xp = *yp; 8 | *yp = temp; 9 | } 10 | 11 | // An optimized version of Bubble Sort 12 | void bubbleSort(int arr[], int n) 13 | { 14 | int i, j; 15 | bool swapped; 16 | for (i = 0; i < n-1; i++) 17 | { 18 | swapped = false; 19 | for (j = 0; j < n-i-1; j++) 20 | { 21 | if (arr[j] > arr[j+1]) 22 | { 23 | swap(&arr[j], &arr[j+1]); 24 | swapped = true; 25 | } 26 | } 27 | 28 | // IF no two elements were swapped by inner loop, then break 29 | if (swapped == false) 30 | break; 31 | } 32 | } 33 | 34 | /* Function to print an array */ 35 | void printArray(int arr[], int size) 36 | { 37 | int i; 38 | for (i = 0; i < size; i++) 39 | cout <<" "<< arr[i]; 40 | cout <<" n"; 41 | } 42 | 43 | // Driver program to test above functions 44 | int main() 45 | { 46 | int arr[] = {64, 34, 25, 12, 22, 11, 90}; 47 | int n = sizeof(arr)/sizeof(arr[0]); 48 | bubbleSort(arr, n); 49 | cout <<"Sorted array: \n"; 50 | printArray(arr, n); 51 | return 0; 52 | } 53 | -------------------------------------------------------------------------------- /Sorting/Bubble Sort/Bubblesort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Bubble Sort 2 | 3 | def bubbleSort(arr): 4 | n = len(arr) 5 | 6 | # Traverse through all array elements 7 | for i in range(n-1): 8 | # range(n) also work but outer loop will repeat one time more than needed. 9 | 10 | # Last i elements are already in place 11 | for j in range(0, n-i-1): 12 | 13 | # traverse the array from 0 to n-i-1 14 | # Swap if the element found is greater 15 | # than the next element 16 | if arr[j] > arr[j + 1] : 17 | arr[j], arr[j + 1] = arr[j + 1], arr[j] 18 | 19 | # Driver code to test above 20 | arr = [64, 34, 25, 12, 22, 11, 90] 21 | 22 | bubbleSort(arr) 23 | 24 | print ("Sorted array is:") 25 | for i in range(len(arr)): 26 | print ("% d" % arr[i]), 27 | 28 | -------------------------------------------------------------------------------- /Sorting/CountingSort/CountingSort.cs: -------------------------------------------------------------------------------- 1 | // C# implementation of Counting Sort 2 | using System; 3 | 4 | class GFG { 5 | 6 | static void countsort(char[] arr) 7 | { 8 | int n = arr.Length; 9 | 10 | // The output character array that 11 | // will have sorted arr 12 | char[] output = new char[n]; 13 | 14 | // Create a count array to store 15 | // count of individual characters 16 | // and initialize count array as 0 17 | int[] count = new int[256]; 18 | 19 | for (int i = 0; i < 256; ++i) 20 | count[i] = 0; 21 | 22 | // store count of each character 23 | for (int i = 0; i < n; ++i) 24 | ++count[arr[i]]; 25 | 26 | // Change count[i] so that count[i] 27 | // now contains actual position of 28 | // this character in output array 29 | for (int i = 1; i <= 255; ++i) 30 | count[i] += count[i - 1]; 31 | 32 | // Build the output character array 33 | // To make it stable we are operating in reverse order. 34 | for (int i = n - 1; i >= 0; i--) { 35 | output[count[arr[i]] - 1] = arr[i]; 36 | --count[arr[i]]; 37 | } 38 | 39 | // Copy the output array to arr, so 40 | // that arr now contains sorted 41 | // characters 42 | for (int i = 0; i < n; ++i) 43 | arr[i] = output[i]; 44 | } 45 | 46 | // Driver method 47 | public static void Main() 48 | { 49 | 50 | char[] arr = { 'g', 'e', 'e', 'k', 's', 'f', 'o', 51 | 'r', 'g', 'e', 'e', 'k', 's' }; 52 | 53 | countsort(arr); 54 | 55 | Console.Write("Sorted character array is "); 56 | for (int i = 0; i < arr.Length; ++i) 57 | Console.Write(arr[i]); 58 | } 59 | } 60 | 61 | // This code is contributed by Sam007. 62 | -------------------------------------------------------------------------------- /Sorting/CountingSort/CountingSort.js: -------------------------------------------------------------------------------- 1 | function countingSort(arr, min, max) 2 | { 3 | var i, z = 0, count = []; 4 | 5 | for (i = min; i <= max; i++) { 6 | count[i] = 0; 7 | } 8 | 9 | for (i=0; i < arr.length; i++) { 10 | count[arr[i]]++; 11 | } 12 | 13 | for (i = min; i <= max; i++) { 14 | while (count[i]-- > 0) { 15 | arr[z++] = i; 16 | } 17 | } 18 | return arr; 19 | } 20 | var arra = [3, 0, 2, 5, 4, 1]; 21 | console.log(arra.length); 22 | console.log("Original Array Elements"); 23 | console.log(arra); 24 | console.log("Sorted Array Elements"); 25 | console.log(countingSort(arra, 0, 5)); 26 | -------------------------------------------------------------------------------- /Sorting/CountingSort/CountingSort.kt: -------------------------------------------------------------------------------- 1 | fun counting_sort(A: Array, max: Int) { 2 | // Array in which result will store 3 | var B = Array(A.size, { 0 }) 4 | // count array 5 | var C = Array(max, { 0 }) 6 | for (i in 0..A.size - 1) { 7 | //count the no. of occurrence of a 8 | //particular element store in count array 9 | C[A[i] - 1] = C[A[i] - 1] + 1 10 | } 11 | for (i in 1..C.size - 1) { 12 | // calculate commutative sum 13 | C[i] = C[i] + C[i - 1] 14 | } 15 | for (i in A.size - 1 downTo 0) { 16 | // place the element at its position 17 | B[C[A[i] - 1] - 1] = A[i] 18 | // decrease the occurrence of the element by 1 19 | C[A[i] - 1] = C[A[i] - 1] - 1 20 | } 21 | println("After sorting :") 22 | for (i in B) { 23 | print("$i ") 24 | } 25 | 26 | } 27 | 28 | fun main(arg: Array) { 29 | print("Enter no. of elements :") 30 | var n = readLine()!!.toInt() 31 | 32 | println("Enter elements : ") 33 | var A = Array(n, { 0 }) 34 | for (i in 0 until n) 35 | A[i] = readLine()!!.toInt() 36 | // calculate maximum element from array 37 | var max = A[0]; 38 | for (i in A) { 39 | if (i > max) { 40 | max = i 41 | } 42 | } 43 | counting_sort(A, max) 44 | } 45 | -------------------------------------------------------------------------------- /Sorting/CountingSort/CountingSort.py: -------------------------------------------------------------------------------- 1 | # Python program for counting sort 2 | 3 | # The main function that sort the given string arr[] in 4 | # alphabetical order 5 | def countSort(arr): 6 | 7 | # The output character array that will have sorted arr 8 | output = [0 for i in range(len(arr))] 9 | 10 | # Create a count array to store count of individual 11 | # characters and initialize count array as 0 12 | count = [0 for i in range(256)] 13 | 14 | # For storing the resulting answer since the 15 | # string is immutable 16 | ans = ["" for _ in arr] 17 | 18 | # Store count of each character 19 | for i in arr: 20 | count[ord(i)] += 1 21 | 22 | # Change count[i] so that count[i] now contains actual 23 | # position of this character in output array 24 | for i in range(256): 25 | count[i] += count[i-1] 26 | 27 | # Build the output character array 28 | for i in range(len(arr)): 29 | output[count[ord(arr[i])]-1] = arr[i] 30 | count[ord(arr[i])] -= 1 31 | 32 | # Copy the output array to arr, so that arr now 33 | # contains sorted characters 34 | for i in range(len(arr)): 35 | ans[i] = output[i] 36 | return ans 37 | 38 | # Driver program to test above function 39 | arr = "geeksforgeeks" 40 | ans = countSort(arr) 41 | print("Sorted character array is % s" %("".join(ans))) 42 | 43 | # This code is contributed by Nikhil Kumar Singh 44 | -------------------------------------------------------------------------------- /Sorting/CountingSort/Counting_sort.c: -------------------------------------------------------------------------------- 1 | // C Program for counting sort 2 | #include 3 | #include 4 | #define RANGE 255 5 | 6 | // The main function that sort the given string arr[] in 7 | // alphabetical order 8 | void countSort(char arr[]) 9 | { 10 | // The output character array that will have sorted arr 11 | char output[strlen(arr)]; 12 | 13 | // Create a count array to store count of individual 14 | // characters and initialize count array as 0 15 | int count[RANGE + 1], i; 16 | memset(count, 0, sizeof(count)); 17 | 18 | // Store count of each character 19 | for (i = 0; arr[i]; ++i) 20 | ++count[arr[i]]; 21 | 22 | // Change count[i] so that count[i] now contains actual 23 | // position of this character in output array 24 | for (i = 1; i <= RANGE; ++i) 25 | count[i] += count[i - 1]; 26 | 27 | // Build the output character array 28 | for (i = 0; arr[i]; ++i) { 29 | output[count[arr[i]] - 1] = arr[i]; 30 | --count[arr[i]]; 31 | } 32 | 33 | /* 34 | For Stable algorithm 35 | for (i = sizeof(arr)-1; i>=0; --i) 36 | { 37 | output[count[arr[i]]-1] = arr[i]; 38 | --count[arr[i]]; 39 | } 40 | 41 | For Logic : See implementation 42 | */ 43 | 44 | // Copy the output array to arr, so that arr now 45 | // contains sorted characters 46 | for (i = 0; arr[i]; ++i) 47 | arr[i] = output[i]; 48 | } 49 | 50 | // Driver program to test above function 51 | int main() 52 | { 53 | char arr[] = "geeksforgeeks"; //"applepp"; 54 | 55 | countSort(arr); 56 | 57 | printf("Sorted character array is %sn", arr); 58 | return 0; 59 | } 60 | -------------------------------------------------------------------------------- /Sorting/CountingSort/countingsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | #define RANGE 255 5 | 6 | void countSort(char arr[]) 7 | { 8 | 9 | char output[strlen(arr)]; 10 | 11 | 12 | int count[RANGE + 1], i; 13 | memset(count, 0, sizeof(count)); 14 | 15 | 16 | for (i = 0; arr[i]; ++i) 17 | ++count[arr[i]]; 18 | 19 | 20 | count[i] += count[i - 1]; 21 | 22 | 23 | for (i = 0; arr[i]; ++i) { 24 | output[count[arr[i]] - 1] = arr[i]; 25 | --count[arr[i]]; 26 | } 27 | 28 | 29 | for (i = 0; arr[i]; ++i) 30 | arr[i] = output[i]; 31 | } 32 | 33 | 34 | int main() 35 | { 36 | char arr[] = "geeksforgeeks"; 37 | 38 | countSort(arr); 39 | 40 | cout << "Sorted character array is " << arr; 41 | return 0; 42 | } 43 | -------------------------------------------------------------------------------- /Sorting/CountingSort/countingsort.java: -------------------------------------------------------------------------------- 1 | import java.util.Arrays; 2 | 3 | class countingsort 4 | { 5 | void countingsort(int arr[]) 6 | { 7 | int max= Arrays.stream(arr).max().getAsInt() ; 8 | int min=Arrays.stream(arr).min().getAsInt() ; 9 | int range=max-min+1; 10 | int count[]=new int[range]; 11 | int len=arr.length; 12 | for (int i=0;i=0;i--) 22 | { 23 | answer[count[arr[i]-min]-1]=arr[i]; 24 | count[arr[i]-min]--; 25 | } 26 | for (int ele:answer) 27 | { 28 | System.out.print(ele+" "); 29 | } 30 | } 31 | public static void main(String[] args) { 32 | int arr[]=new int[]{5,3,7,1,10}; 33 | countingsort count=new countingsort(); 34 | count.countingsort(arr); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /Sorting/Cycle Sort/CycleSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void sort(int a[], int n) 3 | { 4 | int writes = 0,start,element,pos,temp,i; 5 | 6 | for (start = 0; start <= n - 2; start++) { 7 | element = a[start]; 8 | pos = start; 9 | for (i = start + 1; i < n; i++) 10 | if (a[i] < element) 11 | pos++; 12 | if (pos == start) 13 | continue; 14 | while (element == a[pos]) 15 | pos += 1; 16 | if (pos != start) { 17 | //swap(element, a[pos]); 18 | temp = element; 19 | element = a[pos]; 20 | a[pos] = temp; 21 | writes++; 22 | } 23 | while (pos != start) { 24 | pos = start; 25 | for (i = start + 1; i < n; i++) 26 | if (a[i] < element) 27 | pos += 1; 28 | while (element == a[pos]) 29 | pos += 1; 30 | if (element != a[pos]) { 31 | temp = element; 32 | element = a[pos]; 33 | a[pos] = temp; 34 | writes++; 35 | } 36 | } 37 | } 38 | 39 | } 40 | 41 | int main() 42 | { 43 | int a[] = {1, 9, 2, 4, 2, 10, 45, 3, 2}; 44 | int n = sizeof(a) / sizeof(a[0]),i; 45 | sort(a, n); 46 | printf("After sort, array : "); 47 | for (i = 0; i < n; i++) 48 | printf("%d ",a[i]); 49 | return 0; 50 | } -------------------------------------------------------------------------------- /Sorting/Cycle Sort/CycleSort.js: -------------------------------------------------------------------------------- 1 | function cycleSort(array) { 2 | // loop from the beginning of the array to the second to last item 3 | for (let currentIndex = 0; currentIndex < array.length - 1; currentIndex++) { 4 | // save the value of the item at the currentIndex 5 | let item = array[currentIndex] 6 | 7 | let currentIndexCopy = currentIndex 8 | // loop through all indexes that proceed the currentIndex 9 | for (let i = currentIndex + 1; i < array.length; i++) 10 | if (array[i] < item) 11 | currentIndexCopy++ 12 | 13 | // if currentIndexCopy has not changed, the item at the currentIndex is already in the correct currentIndexCopy 14 | if (currentIndexCopy == currentIndex) 15 | continue 16 | 17 | // skip duplicates 18 | while (item == array[currentIndexCopy]) 19 | currentIndexCopy++ 20 | 21 | // swap 22 | let temp = array[currentIndexCopy] 23 | array[currentIndexCopy] = item 24 | item = temp 25 | 26 | // repeat above steps as long as we can find values to swap 27 | while (currentIndexCopy != currentIndex) { 28 | currentIndexCopy = currentIndex 29 | // loop through all indexes that proceed the currentIndex 30 | for (let i = currentIndex + 1; i < array.length; i++) 31 | if (array[i] < item) 32 | currentIndexCopy++ 33 | 34 | // skip duplicates 35 | while (item == array[currentIndexCopy]) 36 | currentIndexCopy++ 37 | 38 | // swap 39 | temp = array[currentIndexCopy] 40 | array[currentIndexCopy] = item 41 | item = temp 42 | } 43 | } 44 | } 45 | 46 | let array = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8] 47 | cycleSort(array) 48 | alert(array) 49 | -------------------------------------------------------------------------------- /Sorting/Cycle Sort/Cyclesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | void sort(int a[], int n) 3 | { 4 | int writes = 0,start,element,pos,temp,i; 5 | 6 | for (start = 0; start <= n - 2; start++) { 7 | element = a[start]; 8 | pos = start; 9 | for (i = start + 1; i < n; i++) 10 | if (a[i] < element) 11 | pos++; 12 | if (pos == start) 13 | continue; 14 | while (element == a[pos]) 15 | pos += 1; 16 | if (pos != start) { 17 | //swap(element, a[pos]); 18 | temp = element; 19 | element = a[pos]; 20 | a[pos] = temp; 21 | writes++; 22 | } 23 | while (pos != start) { 24 | pos = start; 25 | for (i = start + 1; i < n; i++) 26 | if (a[i] < element) 27 | pos += 1; 28 | while (element == a[pos]) 29 | pos += 1; 30 | if (element != a[pos]) { 31 | temp = element; 32 | element = a[pos]; 33 | a[pos] = temp; 34 | writes++; 35 | } 36 | } 37 | } 38 | 39 | } 40 | 41 | int main() 42 | { 43 | int a[] = {1, 9, 2, 4, 2, 10, 45, 3, 2}; 44 | int n = sizeof(a) / sizeof(a[0]),i; 45 | sort(a, n); 46 | printf("After sort, array : "); 47 | for (i = 0; i < n; i++) 48 | printf("%d ",a[i]); 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /Sorting/Cycle Sort/Cyclesort.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class Cyclesort 4 | { 5 | static void sort(int a[], int n) 6 | { 7 | int writes = 0,start,element,pos,temp,i; 8 | 9 | for (start = 0; start <= n - 2; start++) { 10 | element = a[start]; 11 | pos = start; 12 | for (i = start + 1; i < n; i++) 13 | if (a[i] < element) 14 | pos++; 15 | if (pos == start) 16 | continue; 17 | while (element == a[pos]) 18 | pos += 1; 19 | if (pos != start) { 20 | //swap(element, a[pos]); 21 | temp = element; 22 | element = a[pos]; 23 | a[pos] = temp; 24 | writes++; 25 | } 26 | while (pos != start) { 27 | pos = start; 28 | for (i = start + 1; i < n; i++) 29 | if (a[i] < element) 30 | pos += 1; 31 | while (element == a[pos]) 32 | pos += 1; 33 | if (element != a[pos]) { 34 | temp = element; 35 | element = a[pos]; 36 | a[pos] = temp; 37 | writes++; 38 | } 39 | } 40 | } 41 | } 42 | public static void main(String[] args) 43 | { 44 | int arr[] = new int[5]; 45 | Scanner in = new Scanner(System.in); 46 | System.out.println("enter no of elements you want to sort"); 47 | int n = in.nextInt(); 48 | System.out.println("Enter numbers of the array"); 49 | for(int i =0;i 3 | 4 | using namespace std; 5 | 6 | // To heapify a subtree rooted with node i which is 7 | // an index in arr[]. n is size of heap 8 | void heapify(int arr[], int n, int i) 9 | { 10 | int largest = i; // Initialize largest as root 11 | int l = 2 * i + 1; // left = 2*i + 1 12 | int r = 2 * i + 2; // right = 2*i + 2 13 | 14 | // If left child is larger than root 15 | if (l < n && arr[l] > arr[largest]) 16 | largest = l; 17 | 18 | // If right child is larger than largest so far 19 | if (r < n && arr[r] > arr[largest]) 20 | largest = r; 21 | 22 | // If largest is not root 23 | if (largest != i) { 24 | swap(arr[i], arr[largest]); 25 | 26 | // Recursively heapify the affected sub-tree 27 | heapify(arr, n, largest); 28 | } 29 | } 30 | 31 | // main function to do heap sort 32 | void heapSort(int arr[], int n) 33 | { 34 | // Build heap (rearrange array) 35 | for (int i = n / 2 - 1; i >= 0; i--) 36 | heapify(arr, n, i); 37 | 38 | // One by one extract an element from heap 39 | for (int i = n - 1; i > 0; i--) { 40 | // Move current root to end 41 | swap(arr[0], arr[i]); 42 | 43 | // call max heapify on the reduced heap 44 | heapify(arr, i, 0); 45 | } 46 | } 47 | 48 | /* A utility function to print array of size n */ 49 | void printArray(int arr[], int n) 50 | { 51 | for (int i = 0; i < n; ++i) 52 | cout << arr[i] << " "; 53 | cout << "\n"; 54 | } 55 | 56 | // Driver code 57 | int main() 58 | { 59 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 60 | int n = sizeof(arr) / sizeof(arr[0]); 61 | 62 | heapSort(arr, n); 63 | 64 | cout << "Sorted array is \n"; 65 | printArray(arr, n); 66 | } 67 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/HeapSort.cs: -------------------------------------------------------------------------------- 1 | // C# program for implementation of Heap Sort 2 | using System; 3 | 4 | public class HeapSort { 5 | public void sort(int[] arr) 6 | { 7 | int n = arr.Length; 8 | 9 | // Build heap (rearrange array) 10 | for (int i = n / 2 - 1; i >= 0; i--) 11 | heapify(arr, n, i); 12 | 13 | // One by one extract an element from heap 14 | for (int i = n - 1; i > 0; i--) { 15 | // Move current root to end 16 | int temp = arr[0]; 17 | arr[0] = arr[i]; 18 | arr[i] = temp; 19 | 20 | // call max heapify on the reduced heap 21 | heapify(arr, i, 0); 22 | } 23 | } 24 | 25 | // To heapify a subtree rooted with node i which is 26 | // an index in arr[]. n is size of heap 27 | void heapify(int[] arr, int n, int i) 28 | { 29 | int largest = i; // Initialize largest as root 30 | int l = 2 * i + 1; // left = 2*i + 1 31 | int r = 2 * i + 2; // right = 2*i + 2 32 | 33 | // If left child is larger than root 34 | if (l < n && arr[l] > arr[largest]) 35 | largest = l; 36 | 37 | // If right child is larger than largest so far 38 | if (r < n && arr[r] > arr[largest]) 39 | largest = r; 40 | 41 | // If largest is not root 42 | if (largest != i) { 43 | int swap = arr[i]; 44 | arr[i] = arr[largest]; 45 | arr[largest] = swap; 46 | 47 | // Recursively heapify the affected sub-tree 48 | heapify(arr, n, largest); 49 | } 50 | } 51 | 52 | /* A utility function to print array of size n */ 53 | static void printArray(int[] arr) 54 | { 55 | int n = arr.Length; 56 | for (int i = 0; i < n; ++i) 57 | Console.Write(arr[i] + " "); 58 | Console.Read(); 59 | } 60 | 61 | // Driver code 62 | public static void Main() 63 | { 64 | int[] arr = { 12, 11, 13, 5, 6, 7 }; 65 | int n = arr.Length; 66 | 67 | HeapSort ob = new HeapSort(); 68 | ob.sort(arr); 69 | 70 | Console.WriteLine("Sorted array is"); 71 | printArray(arr); 72 | } 73 | } 74 | 75 | // This code is contributed 76 | // by Akanksha Rai(Abby_akku) 77 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/HeapSort.java: -------------------------------------------------------------------------------- 1 | public class HeapSort { 2 | public void sort(int arr[]) 3 | { 4 | int n = arr.length; 5 | 6 | // Build heap (rearrange array) 7 | for (int i = n / 2 - 1; i >= 0; i--) 8 | heapify(arr, n, i); 9 | 10 | // One by one extract an element from heap 11 | for (int i = n - 1; i > 0; i--) { 12 | // Move current root to end 13 | int temp = arr[0]; 14 | arr[0] = arr[i]; 15 | arr[i] = temp; 16 | 17 | // call max heapify on the reduced heap 18 | heapify(arr, i, 0); 19 | } 20 | } 21 | 22 | // To heapify a subtree rooted with node i which is 23 | // an index in arr[]. n is size of heap 24 | void heapify(int arr[], int n, int i) 25 | { 26 | int largest = i; // Initialize largest as root 27 | int l = 2 * i + 1; // left = 2*i + 1 28 | int r = 2 * i + 2; // right = 2*i + 2 29 | 30 | // If left child is larger than root 31 | if (l < n && arr[l] > arr[largest]) 32 | largest = l; 33 | 34 | // If right child is larger than largest so far 35 | if (r < n && arr[r] > arr[largest]) 36 | largest = r; 37 | 38 | // If largest is not root 39 | if (largest != i) { 40 | int swap = arr[i]; 41 | arr[i] = arr[largest]; 42 | arr[largest] = swap; 43 | 44 | // Recursively heapify the affected sub-tree 45 | heapify(arr, n, largest); 46 | } 47 | } 48 | 49 | /* A utility function to print array of size n */ 50 | static void printArray(int arr[]) 51 | { 52 | int n = arr.length; 53 | for (int i = 0; i < n; ++i) 54 | System.out.print(arr[i] + " "); 55 | System.out.println(); 56 | } 57 | 58 | // Driver code 59 | public static void main(String args[]) 60 | { 61 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 62 | int n = arr.length; 63 | 64 | HeapSort ob = new HeapSort(); 65 | ob.sort(arr); 66 | 67 | System.out.println("Sorted array is"); 68 | printArray(arr); 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/HeapSort.js: -------------------------------------------------------------------------------- 1 | 75 | -------------------------------------------------------------------------------- /Sorting/Heap Sort/HeapSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of heap Sort 2 | 3 | # To heapify subtree rooted at index i. 4 | # n is size of heap 5 | 6 | 7 | def heapify(arr, n, i): 8 | largest = i # Initialize largest as root 9 | l = 2 * i + 1 # left = 2*i + 1 10 | r = 2 * i + 2 # right = 2*i + 2 11 | 12 | # See if left child of root exists and is 13 | # greater than root 14 | if l < n and arr[largest] < arr[l]: 15 | largest = l 16 | 17 | # See if right child of root exists and is 18 | # greater than root 19 | if r < n and arr[largest] < arr[r]: 20 | largest = r 21 | 22 | # Change root, if needed 23 | if largest != i: 24 | arr[i], arr[largest] = arr[largest], arr[i] # swap 25 | 26 | # Heapify the root. 27 | heapify(arr, n, largest) 28 | 29 | # The main function to sort an array of given size 30 | 31 | 32 | def heapSort(arr): 33 | n = len(arr) 34 | 35 | # Build a maxheap. 36 | for i in range(n//2 - 1, -1, -1): 37 | heapify(arr, n, i) 38 | 39 | # One by one extract elements 40 | for i in range(n-1, 0, -1): 41 | arr[i], arr[0] = arr[0], arr[i] # swap 42 | heapify(arr, i, 0) 43 | 44 | 45 | # Driver code 46 | arr = [12, 11, 13, 5, 6, 7] 47 | heapSort(arr) 48 | n = len(arr) 49 | print("Sorted array is") 50 | for i in range(n): 51 | print("%d" % arr[i]), 52 | # This code is contributed by Mohit Kumra 53 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/InsertionSort.c: -------------------------------------------------------------------------------- 1 | // C program for insertion sort 2 | #include 3 | #include 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) { 10 | key = arr[i]; 11 | j = i - 1; 12 | 13 | /* Move elements of arr[0..i-1], that are 14 | greater than key, to one position ahead 15 | of their current position */ 16 | while (j >= 0 && arr[j] > key) { 17 | arr[j + 1] = arr[j]; 18 | j = j - 1; 19 | } 20 | arr[j + 1] = key; 21 | } 22 | } 23 | 24 | // A utility function to print an array of size n 25 | void printArray(int arr[], int n) 26 | { 27 | int i; 28 | for (i = 0; i < n; i++) 29 | printf("%d ", arr[i]); 30 | printf("\n"); 31 | } 32 | 33 | /* Driver program to test insertion sort */ 34 | int main() 35 | { 36 | int arr[] = { 12, 11, 13, 5, 6 }; 37 | int n = sizeof(arr) / sizeof(arr[0]); 38 | 39 | insertionSort(arr, n); 40 | printArray(arr, n); 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/InsertionSort.java: -------------------------------------------------------------------------------- 1 | // Java program for implementation of Insertion Sort 2 | class InsertionSort { 3 | /*Function to sort array using insertion sort*/ 4 | void sort(int arr[]) 5 | { 6 | int n = arr.length; 7 | for (int i = 1; i < n; ++i) { 8 | int key = arr[i]; 9 | int j = i - 1; 10 | 11 | /* Move elements of arr[0..i-1], that are 12 | greater than key, to one position ahead 13 | of their current position */ 14 | while (j >= 0 && arr[j] > key) { 15 | arr[j + 1] = arr[j]; 16 | j = j - 1; 17 | } 18 | arr[j + 1] = key; 19 | } 20 | } 21 | 22 | /* A utility function to print array of size n*/ 23 | static void printArray(int arr[]) 24 | { 25 | int n = arr.length; 26 | for (int i = 0; i < n; ++i) 27 | System.out.print(arr[i] + " "); 28 | 29 | System.out.println(); 30 | } 31 | 32 | // Driver method 33 | public static void main(String args[]) 34 | { 35 | int arr[] = { 22, 74, 98, 72, 24, 34, 90, 10, 68, 15, 57, 6, 47}; 36 | InsertionSort ob = new InsertionSort(); 37 | ob.sort(arr); 38 | 39 | printArray(arr); 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/InsertionSort.js: -------------------------------------------------------------------------------- 1 | 44 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/InsertionSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of Insertion Sort 2 | 3 | # Function to do insertion sort 4 | def insertionSort(arr): 5 | 6 | # Traverse through 1 to len(arr) 7 | for i in range(1, len(arr)): 8 | 9 | key = arr[i] 10 | 11 | # Move elements of arr[0..i-1], that are 12 | # greater than key, to one position ahead 13 | # of their current position 14 | j = i-1 15 | while j >= 0 and key < arr[j] : 16 | arr[j + 1] = arr[j] 17 | j -= 1 18 | arr[j + 1] = key 19 | 20 | 21 | # Driver code to test above 22 | arr = [12, 11, 13, 5, 6] 23 | insertionSort(arr) 24 | for i in range(len(arr)): 25 | print ("% d" % arr[i]) 26 | 27 | # This code is contributed by Mohit Kumra 28 | -------------------------------------------------------------------------------- /Sorting/Insertion Sort/Insertionsort.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for insertion sort 2 | #include 3 | using namespace std; 4 | 5 | /* Function to sort an array using insertion sort*/ 6 | void insertionSort(int arr[], int n) 7 | { 8 | int i, key, j; 9 | for (i = 1; i < n; i++) 10 | { 11 | key = arr[i]; 12 | j = i - 1; 13 | 14 | /* Move elements of arr[0..i-1], that are 15 | greater than key, to one position ahead 16 | of their current position */ 17 | while (j >= 0 && arr[j] > key) 18 | { 19 | arr[j + 1] = arr[j]; 20 | j = j - 1; 21 | } 22 | arr[j + 1] = key; 23 | } 24 | } 25 | 26 | // A utility function to print an array of size n 27 | void printArray(int arr[], int n) 28 | { 29 | int i; 30 | for (i = 0; i < n; i++) 31 | cout << arr[i] << " "; 32 | cout << endl; 33 | } 34 | 35 | /* Driver code */ 36 | int main() 37 | { 38 | int arr[] = { 12, 11, 13, 5, 6 }; 39 | int n = sizeof(arr) / sizeof(arr[0]); 40 | 41 | insertionSort(arr, n); 42 | printArray(arr, n); 43 | 44 | return 0; 45 | } 46 | 47 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/MergeSort.java: -------------------------------------------------------------------------------- 1 | class MergeSort { 2 | public static void mergeSort(int[] a, int n) { 3 | if (n < 2) { 4 | return; 5 | } 6 | int mid = n / 2; 7 | int[] l = new int[mid]; 8 | int[] r = new int[n - mid]; 9 | 10 | for (int i = 0; i < mid; i++) { 11 | l[i] = a[i]; 12 | } 13 | for (int i = mid; i < n; i++) { 14 | r[i - mid] = a[i]; 15 | } 16 | mergeSort(l, mid); 17 | mergeSort(r, n - mid); 18 | 19 | merge(a, l, r, mid, n - mid); 20 | } 21 | 22 | public static void merge(int[] a, int[] l, int[] r, int left, int right) { 23 | int i = 0, j = 0, k = 0; 24 | while (i < left && j < right) { 25 | if (l[i] <= r[j]) { 26 | a[k++] = l[i++]; 27 | } 28 | else { 29 | a[k++] = r[j++]; 30 | } 31 | } 32 | while (i < left) { 33 | a[k++] = l[i++]; 34 | } 35 | while (j < right) { 36 | a[k++] = r[j++]; 37 | } 38 | } 39 | 40 | /* A utility function to print array of size n*/ 41 | static void printArray(int arr[]) 42 | { 43 | int n = arr.length; 44 | for (int i = 0; i < n; ++i) 45 | System.out.print(arr[i] + " "); 46 | 47 | System.out.println(); 48 | } 49 | 50 | // Driver method 51 | public static void main(String args[]) 52 | { 53 | int arr[] = { 22, 74, 98, 72, 24, 34, 90, 10, 68, 15, 57, 6, 47}; 54 | MergeSort.mergeSort(arr, arr.length); 55 | 56 | printArray(arr); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/MergeSort.kt: -------------------------------------------------------------------------------- 1 | fun mergeSort(list: List): List { 2 | if (list.size <= 1) { 3 | return list 4 | } 5 | 6 | val middle = list.size / 2 7 | var left = list.subList(0,middle); 8 | var right = list.subList(middle,list.size); 9 | 10 | return merge(mergeSort(left), mergeSort(right)) 11 | } 12 | fun merge(left: List, right: List): List { 13 | var indexLeft = 0 14 | var indexRight = 0 15 | var newList : MutableList = mutableListOf() 16 | 17 | while (indexLeft < left.count() && indexRight < right.count()) { 18 | if (left[indexLeft] <= right[indexRight]) { 19 | newList.add(left[indexLeft]) 20 | indexLeft++ 21 | } else { 22 | newList.add(right[indexRight]) 23 | indexRight++ 24 | } 25 | } 26 | 27 | while (indexLeft < left.size) { 28 | newList.add(left[indexLeft]) 29 | indexLeft++ 30 | } 31 | 32 | while (indexRight < right.size) { 33 | newList.add(right[indexRight]) 34 | indexRight++ 35 | } 36 | return newList; 37 | } 38 | 39 | fun main(args: Array) { 40 | val numbers = mutableListOf(38,27,43,3,9,82,10) 41 | val sortedList = mergeSort(numbers) 42 | println("Unsorted: $numbers") 43 | println("Sorted: $sortedList") 44 | } 45 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/MergeSort.py: -------------------------------------------------------------------------------- 1 | # Python program for implementation of MergeSort 2 | 3 | # Merges two subarrays of arr[]. 4 | # First subarray is arr[l..m] 5 | # Second subarray is arr[m+1..r] 6 | 7 | 8 | def merge(arr, l, m, r): 9 | n1 = m - l + 1 10 | n2 = r - m 11 | 12 | # create temp arrays 13 | L = [0] * (n1) 14 | R = [0] * (n2) 15 | 16 | # Copy data to temp arrays L[] and R[] 17 | for i in range(0, n1): 18 | L[i] = arr[l + i] 19 | 20 | for j in range(0, n2): 21 | R[j] = arr[m + 1 + j] 22 | 23 | # Merge the temp arrays back into arr[l..r] 24 | i = 0 # Initial index of first subarray 25 | j = 0 # Initial index of second subarray 26 | k = l # Initial index of merged subarray 27 | 28 | while i < n1 and j < n2: 29 | if L[i] <= R[j]: 30 | arr[k] = L[i] 31 | i += 1 32 | else: 33 | arr[k] = R[j] 34 | j += 1 35 | k += 1 36 | 37 | # Copy the remaining elements of L[], if there 38 | # are any 39 | while i < n1: 40 | arr[k] = L[i] 41 | i += 1 42 | k += 1 43 | 44 | # Copy the remaining elements of R[], if there 45 | # are any 46 | while j < n2: 47 | arr[k] = R[j] 48 | j += 1 49 | k += 1 50 | 51 | # l is for left index and r is right index of the 52 | # sub-array of arr to be sorted 53 | 54 | 55 | def mergeSort(arr, l, r): 56 | if l < r: 57 | 58 | # Same as (l+r)//2, but avoids overflow for 59 | # large l and h 60 | m = l+(r-l)//2 61 | 62 | # Sort first and second halves 63 | mergeSort(arr, l, m) 64 | mergeSort(arr, m+1, r) 65 | merge(arr, l, m, r) 66 | 67 | 68 | # Driver code to test above 69 | arr = [12, 11, 13, 5, 6, 7] 70 | n = len(arr) 71 | print("Given array is") 72 | for i in range(n): 73 | print("%d" % arr[i]), 74 | 75 | mergeSort(arr, 0, n-1) 76 | print("\n\nSorted array is") 77 | for i in range(n): 78 | print("%d" % arr[i]), 79 | 80 | # This code is contributed by Mohit Kumra 81 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/mergesort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void swapping(int &a, int &b) { 4 | int temp; 5 | temp = a; 6 | a = b; 7 | b = temp; 8 | } 9 | void display(int *array, int size) { 10 | for(int i = 0; i> n; 59 | int arr[n]; 60 | cout << "Enter elements:" << endl; 61 | for(int i = 0; i> arr[i]; 63 | } 64 | cout << "Array before Sorting: "; 65 | display(arr, n); 66 | mergeSort(arr, 0, n-1); 67 | cout << "Array after Sorting: "; 68 | display(arr, n); 69 | } 70 | -------------------------------------------------------------------------------- /Sorting/Merge Sort/mergesort.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | func mergeSort(arr []int) []int { 4 | // Merge sort: Recursively divides the array, comparing subarrays and rebuilding a sorted array. 5 | // Time Complexity: Best - O(n log(n)) Average - O(n log(n)) Worst - O(n log(n)) 6 | 7 | // If the array is less than 2 items long, there is no reason to sort 8 | if len(arr) < 2 { 9 | return arr 10 | } 11 | 12 | // Create the first subarray using the first half of the array to be sorted 13 | firstArr := mergeSort(arr[:len(arr)/2]) 14 | 15 | // Create the second subarray using the remaining half of the array to be sorted 16 | secondArr := mergeSort(arr[len(arr)/2:]) 17 | 18 | // Call the merge function to sort and combine these subarrays 19 | return merge(firstArr, secondArr) 20 | } 21 | 22 | // Function for merging two arrays into a singular array 23 | func merge(arrA []int, arrB []int) []int { 24 | 25 | // Declare an array to store merged version 26 | var mergedArr []int 27 | 28 | // Initialise counters i and j as 0 29 | i, j := 0, 0 30 | 31 | // As while loops are not implemented in Go, we use a for loop to iterate through subarrays 32 | for i < len(arrA) && j < len(arrB) { 33 | // If the value within subarray A is less than that of subarray B 34 | if arrA[i] < arrB[j] { 35 | // Append the value at index i from subarray A to the merged array 36 | mergedArr = append(mergedArr, arrA[i]) 37 | // Increment the counter i (this will step through subarray A) 38 | i++ 39 | // Else (the values are equal or that of A is larger than that of B 40 | } else { 41 | // Append the value at index i from subarray B to the merged array 42 | mergedArr = append(mergedArr, arrB[j]) 43 | // Increment the counter j (this will step through subarray B) 44 | j++ 45 | } 46 | } 47 | 48 | // Both loops will utilise the value that the iterator has become from the previous for loop 49 | for ; i < len(arrA); i++ { 50 | mergedArr = append(mergedArr, arrA[i]) 51 | } 52 | 53 | for ; j < len(arrB); j++ { 54 | mergedArr = append(mergedArr, arrB[j]) 55 | } 56 | 57 | // Return the sorted array 58 | return mergedArr 59 | } 60 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/QuickSort.c: -------------------------------------------------------------------------------- 1 | #include 2 | void quicksort(int number[25],int first,int last){ 3 | int i, j, pivot, temp; 4 | 5 | if(firstnumber[pivot]) 14 | j--; 15 | if(i 4 | #include 5 | using namespace std; 6 | 7 | // This function takes last element 8 | // as pivot, places 9 | // the pivot element at its correct 10 | // position in sorted array, and 11 | // places all smaller (smaller than pivot) 12 | // to left of pivot and all greater 13 | // elements to right of pivot 14 | int partition(int arr[], int low, int high) 15 | { 16 | // pivot 17 | int pivot = arr[high]; 18 | 19 | // Index of smaller element 20 | int i = (low - 1); 21 | 22 | for (int j = low; j <= high - 1; j++) 23 | { 24 | // If current element is smaller 25 | // than or equal to pivot 26 | if (arr[j] <= pivot) { 27 | 28 | // increment index of 29 | // smaller element 30 | i++; 31 | swap(arr[i], arr[j]); 32 | } 33 | } 34 | swap(arr[i + 1], arr[high]); 35 | return (i + 1); 36 | } 37 | 38 | // Generates Random Pivot, swaps pivot with 39 | // end element and calls the partition function 40 | int partition_r(int arr[], int low, int high) 41 | { 42 | // Generate a random number in between 43 | // low .. high 44 | srand(time(NULL)); 45 | int random = low + rand() % (high - low); 46 | 47 | // Swap A[random] with A[high] 48 | swap(arr[random], arr[high]); 49 | 50 | return partition(arr, low, high); 51 | } 52 | 53 | /* The main function that implements 54 | QuickSort 55 | arr[] --> Array to be sorted, 56 | low --> Starting index, 57 | high --> Ending index */ 58 | void quickSort(int arr[], int low, int high) 59 | { 60 | if (low < high) { 61 | 62 | /* pi is partitioning index, 63 | arr[p] is now 64 | at right place */ 65 | int pi = partition_r(arr, low, high); 66 | 67 | // Separately sort elements before 68 | // partition and after partition 69 | quickSort(arr, low, pi - 1); 70 | quickSort(arr, pi + 1, high); 71 | } 72 | } 73 | 74 | /* Function to print an array */ 75 | void printArray(int arr[], int size) 76 | { 77 | int i; 78 | for (i = 0; i < size; i++) 79 | printf("%d ", arr[i]); 80 | printf("\n"); 81 | } 82 | 83 | // Driver Code 84 | int main() 85 | { 86 | int arr[] = { 10, 7, 8, 9, 1, 5 }; 87 | int n = sizeof(arr) / sizeof(arr[0]); 88 | quickSort(arr, 0, n - 1); 89 | printf("Sorted array: \n"); 90 | printArray(arr, n); 91 | return 0; 92 | } 93 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/QuickSort.cs: -------------------------------------------------------------------------------- 1 | // C# program to illustrate 2 | // Randomised Quick sort 3 | using System; 4 | class RandomizedQsort 5 | { 6 | 7 | /* This function takes last element as pivot, 8 | places the pivot element at its correct 9 | position in sorted array, and places all 10 | smaller (smaller than pivot) to left of 11 | pivot and all greater elements to right 12 | of pivot */ 13 | static int partition(int[] arr, int low, int high) 14 | { 15 | 16 | // pivot is chosen randomly 17 | random(arr, low, high); 18 | int pivot = arr[high]; 19 | 20 | int i = (low-1); // index of smaller element 21 | for (int j = low; j < high; j++) 22 | { 23 | 24 | // If current element is smaller than or 25 | // equal to pivot 26 | if (arr[j] < pivot) 27 | { 28 | i++; 29 | 30 | // swap arr[i] and arr[j] 31 | int tempp = arr[i]; 32 | arr[i] = arr[j]; 33 | arr[j] = tempp; 34 | } 35 | } 36 | 37 | // swap arr[i+1] and arr[high] (or pivot) 38 | int tempp2 = arr[i + 1]; 39 | arr[i + 1] = arr[high]; 40 | arr[high] = tempp2; 41 | 42 | return i + 1; 43 | } 44 | 45 | // This Function helps in calculating 46 | // random numbers between low(inclusive) 47 | // and high(inclusive) 48 | static int random(int[] arr, int low, int high) 49 | { 50 | 51 | Random rand = new Random(); 52 | int pivot = rand.Next() % (high - low) + low; 53 | 54 | int tempp1 = arr[pivot]; 55 | arr[pivot] = arr[high]; 56 | arr[high] = tempp1; 57 | 58 | return partition(arr, low, high); 59 | } 60 | 61 | /* The main function that implements Quicksort() 62 | arr[] --> Array to be sorted, 63 | low --> Starting index, 64 | high --> Ending index */ 65 | static void sort(int[] arr, int low, int high) 66 | { 67 | if (low < high) 68 | { 69 | /* pi is partitioning index, arr[pi] is 70 | now at right place */ 71 | int pi = partition(arr, low, high); 72 | 73 | // Recursively sort elements before 74 | // partition and after partition 75 | sort(arr, low, pi - 1); 76 | sort(arr, pi + 1, high); 77 | } 78 | } 79 | 80 | /* A utility function to print array of size n */ 81 | static void printArray(int[] arr) 82 | { 83 | int n = arr.Length; 84 | for (int i = 0; i < n; ++i) 85 | Console.Write(arr[i] + " "); 86 | Console.WriteLine(); 87 | } 88 | 89 | // Driver Code 90 | static public void Main () 91 | { 92 | int[] arr = {10, 7, 8, 9, 1, 5}; 93 | int n = arr.Length; 94 | 95 | sort(arr, 0, n-1); 96 | 97 | Console.WriteLine("sorted array"); 98 | printArray(arr); 99 | } 100 | } 101 | 102 | // This code is contributed by shubhamsingh10 103 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/QuickSort.java: -------------------------------------------------------------------------------- 1 | 2 | // Java implementation of QuickSort 3 | import java.io.*; 4 | 5 | class GFG{ 6 | 7 | // A utility function to swap two elements 8 | static void swap(int[] arr, int i, int j) 9 | { 10 | int temp = arr[i]; 11 | arr[i] = arr[j]; 12 | arr[j] = temp; 13 | } 14 | 15 | /* This function takes last element as pivot, places 16 | the pivot element at its correct position in sorted 17 | array, and places all smaller (smaller than pivot) 18 | to left of pivot and all greater elements to right 19 | of pivot */ 20 | static int partition(int[] arr, int low, int high) 21 | { 22 | 23 | // pivot 24 | int pivot = arr[high]; 25 | 26 | // Index of smaller element and 27 | // indicates the right position 28 | // of pivot found so far 29 | int i = (low - 1); 30 | 31 | for(int j = low; j <= high - 1; j++) 32 | { 33 | 34 | // If current element is smaller 35 | // than the pivot 36 | if (arr[j] < pivot) 37 | { 38 | 39 | // Increment index of 40 | // smaller element 41 | i++; 42 | swap(arr, i, j); 43 | } 44 | } 45 | swap(arr, i + 1, high); 46 | return (i + 1); 47 | } 48 | 49 | /* The main function that implements QuickSort 50 | arr[] --> Array to be sorted, 51 | low --> Starting index, 52 | high --> Ending index 53 | */ 54 | static void quickSort(int[] arr, int low, int high) 55 | { 56 | if (low < high) 57 | { 58 | 59 | // pi is partitioning index, arr[p] 60 | // is now at right place 61 | int pi = partition(arr, low, high); 62 | 63 | // Separately sort elements before 64 | // partition and after partition 65 | quickSort(arr, low, pi - 1); 66 | quickSort(arr, pi + 1, high); 67 | } 68 | } 69 | 70 | // Function to print an array 71 | static void printArray(int[] arr, int size) 72 | { 73 | for(int i = 0; i < size; i++) 74 | System.out.print(arr[i] + " "); 75 | 76 | System.out.println(); 77 | } 78 | 79 | // Driver Code 80 | public static void main(String[] args) 81 | { 82 | int[] arr = { 10, 7, 8, 9, 1, 5 }; 83 | int n = arr.length; 84 | 85 | quickSort(arr, 0, n - 1); 86 | System.out.println("Sorted array: "); 87 | printArray(arr, n); 88 | } 89 | } 90 | 91 | // This code is contributed by Ayush Choudhary 92 | -------------------------------------------------------------------------------- /Sorting/Quick Sort/QuickSort.py: -------------------------------------------------------------------------------- 1 | # Partition Function 2 | # Takes in an array and the left and right index 3 | # Returns the position of the pivot 4 | def partition(arr,l,r): 5 | 6 | # Pivot is the last element of the list 7 | pivot = arr[r] 8 | # i is the index of the first element of the list 9 | i = l-1 10 | 11 | # Looping through the list 12 | for j in range(l,r): 13 | # If the current element is less than the pivot 14 | # Then swap the current element with the element at index i 15 | if arr[j] <= pivot: 16 | i = i + 1 17 | arr[i],arr[j] = arr[j],arr[i] 18 | # Swap the pivot with the element at index i+1 19 | arr[i+1],arr[r] = arr[r],arr[i+1] 20 | return i+1 21 | 22 | # Quicksort Function 23 | # Takes in an array and the left and right index 24 | # Returns the sorted array 25 | def quicksort(arr,l,r): 26 | 27 | # Base case : if the left index is greater than the right index, then return 28 | if l >= r: 29 | return 30 | 31 | # Calling the partition function to get the position of the pivot 32 | p = partition(arr,l,r) 33 | 34 | # Recursively calling quicksort function on the list before the pivot 35 | quicksort(arr,l,p-1) 36 | # Recursively calling quicksort function on the list after the pivot 37 | quicksort(arr,p+1,r) 38 | 39 | 40 | # Driver Code 41 | lst = [2,4,1,8,5,7,6,3] 42 | quicksort(lst,0,len(lst)-1) 43 | print(lst) 44 | 45 | # Code contributed by Sayan Maiti -------------------------------------------------------------------------------- /Sorting/Radix Sort/RadixSort.cpp: -------------------------------------------------------------------------------- 1 | // Radix Sort in C++ Programming 2 | 3 | #include 4 | using namespace std; 5 | 6 | // Function to get the largest element from an array 7 | int getMax(int array[], int n) { 8 | int max = array[0]; 9 | for (int i = 1; i < n; i++) 10 | if (array[i] > max) 11 | max = array[i]; 12 | return max; 13 | } 14 | 15 | // Using counting sort to sort the elements in the basis of significant places 16 | void countingSort(int array[], int size, int place) { 17 | const int max = 10; 18 | int output[size]; 19 | int count[max]; 20 | 21 | for (int i = 0; i < max; ++i) 22 | count[i] = 0; 23 | 24 | // Calculate count of elements 25 | for (int i = 0; i < size; i++) 26 | count[(array[i] / place) % 10]++; 27 | 28 | // Calculate cumulative count 29 | for (int i = 1; i < max; i++) 30 | count[i] += count[i - 1]; 31 | 32 | // Place the elements in sorted order 33 | for (int i = size - 1; i >= 0; i--) { 34 | output[count[(array[i] / place) % 10] - 1] = array[i]; 35 | count[(array[i] / place) % 10]--; 36 | } 37 | 38 | for (int i = 0; i < size; i++) 39 | array[i] = output[i]; 40 | } 41 | 42 | // Main function to implement radix sort 43 | void radixsort(int array[], int size) { 44 | // Get maximum element 45 | int max = getMax(array, size); 46 | 47 | // Apply counting sort to sort elements based on place value. 48 | for (int place = 1; max / place > 0; place *= 10) 49 | countingSort(array, size, place); 50 | } 51 | 52 | // Print an array 53 | void printArray(int array[], int size) { 54 | int i; 55 | for (i = 0; i < size; i++) 56 | cout << array[i] << " "; 57 | cout << endl; 58 | } 59 | 60 | // Driver code 61 | int main() { 62 | int array[] = {121, 432, 564, 23, 1, 45, 788}; 63 | int n = sizeof(array) / sizeof(array[0]); 64 | radixsort(array, n); 65 | printArray(array, n); 66 | return 0; 67 | } 68 | -------------------------------------------------------------------------------- /Sorting/Radix Sort/RadixSort.cs: -------------------------------------------------------------------------------- 1 | // C# implementation of Radix Sort 2 | using System; 3 | 4 | class GFG { 5 | public static int getMax(int[] arr, int n) 6 | { 7 | int mx = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | if (arr[i] > mx) 10 | mx = arr[i]; 11 | return mx; 12 | } 13 | 14 | // A function to do counting sort of arr[] according to 15 | // the digit represented by exp. 16 | public static void countSort(int[] arr, int n, int exp) 17 | { 18 | int[] output = new int[n]; // output array 19 | int i; 20 | int[] count = new int[10]; 21 | 22 | // initializing all elements of count to 0 23 | for (i = 0; i < 10; i++) 24 | count[i] = 0; 25 | 26 | // Store count of occurrences in count[] 27 | for (i = 0; i < n; i++) 28 | count[(arr[i] / exp) % 10]++; 29 | 30 | // Change count[i] so that count[i] now contains 31 | // actual 32 | // position of this digit in output[] 33 | for (i = 1; i < 10; i++) 34 | count[i] += count[i - 1]; 35 | 36 | // Build the output array 37 | for (i = n - 1; i >= 0; i--) { 38 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 39 | count[(arr[i] / exp) % 10]--; 40 | } 41 | 42 | // Copy the output array to arr[], so that arr[] now 43 | // contains sorted numbers according to current 44 | // digit 45 | for (i = 0; i < n; i++) 46 | arr[i] = output[i]; 47 | } 48 | 49 | // The main function to that sorts arr[] of size n using 50 | // Radix Sort 51 | public static void radixsort(int[] arr, int n) 52 | { 53 | // Find the maximum number to know number of digits 54 | int m = getMax(arr, n); 55 | 56 | // Do counting sort for every digit. Note that 57 | // instead of passing digit number, exp is passed. 58 | // exp is 10^i where i is current digit number 59 | for (int exp = 1; m / exp > 0; exp *= 10) 60 | countSort(arr, n, exp); 61 | } 62 | 63 | // A utility function to print an array 64 | public static void print(int[] arr, int n) 65 | { 66 | for (int i = 0; i < n; i++) 67 | Console.Write(arr[i] + " "); 68 | } 69 | 70 | // Driver Code 71 | public static void Main() 72 | { 73 | int[] arr = { 170, 45, 75, 90, 802, 24, 2, 66 }; 74 | int n = arr.Length; 75 | 76 | // Function Call 77 | radixsort(arr, n); 78 | print(arr, n); 79 | } 80 | 81 | // This code is contributed by DrRoot_ 82 | } 83 | -------------------------------------------------------------------------------- /Sorting/Radix Sort/RadixSort.java: -------------------------------------------------------------------------------- 1 | import java.io.*; 2 | import java.util.*; 3 | 4 | public class RadiaxSort { 5 | // A utility function to get maximum value in arr[] 6 | static int getMax(int arr[], int n) { 7 | int mx = arr[0]; 8 | for (int i = 1; i < n; i++) 9 | if (arr[i] > mx) 10 | mx = arr[i]; 11 | return mx; 12 | } 13 | 14 | // A function to do counting sort of arr[] according to 15 | // the digit represented by exp. 16 | static void countSort(int arr[], int n, int exp) { 17 | int output[] = new int[n]; 18 | int i; 19 | int count[] = new int[10]; 20 | Arrays.fill(count, 0); 21 | for (i = 0; i < n; i++) 22 | count[(arr[i] / exp) % 10]++; 23 | for (i = 1; i < 10; i++) 24 | count[i] += count[i - 1]; 25 | for (i = n - 1; i >= 0; i--) { 26 | output[count[(arr[i] / exp) % 10] - 1] = arr[i]; 27 | count[(arr[i] / exp) % 10]--; 28 | } 29 | for (i = 0; i < n; i++) 30 | arr[i] = output[i]; 31 | } 32 | 33 | // The main function to that sorts arr[] of size n using 34 | // Radix Sort 35 | static void radixsort(int arr[], int n) { 36 | int m = getMax(arr, n); 37 | for (int exp = 1; m / exp > 0; exp *= 10) 38 | countSort(arr, n, exp); 39 | } 40 | 41 | // A utility function to print an array 42 | static void print(int arr[], int n) { 43 | for (int i = 0; i < n; i++) 44 | System.out.print(arr[i] + " "); 45 | } 46 | 47 | /* Driver Code */ 48 | public static void main(String[] args) { 49 | int arr[] = { 170, 45, 75, 90, 802, 24, 2, 66 }; 50 | int n = arr.length; 51 | radixsort(arr, n); 52 | print(arr, n); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/SelctionSort.java: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/SelectionSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void swap(int *a, int *b) { 5 | int temp = *a; 6 | *a = *b; 7 | *b = temp; 8 | } 9 | 10 | void Array(int array[], int size) { 11 | for (int i = 0; i < size; i++) { 12 | cout << array[i] << " "; 13 | } 14 | cout << endl; 15 | } 16 | 17 | void selectionSort(int array[], int size) { 18 | for (int step = 0; step < size - 1; step++) { 19 | int min = step; 20 | for (int i = step + 1; i < size; i++) { 21 | 22 | if (array[i] < array[min]) 23 | min= i; 24 | } 25 | 26 | swap(&array[min], &array[step]); 27 | } 28 | } 29 | 30 | 31 | int main() { 32 | int data[] = {20, 12, 10, 15, 2}; 33 | int size = sizeof(data) / sizeof(data[0]); 34 | selectionSort(data, size); 35 | cout << "Sorted array in Acsending Order:\n"; 36 | Array(data, size); 37 | } 38 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/SelectionSort.cs: -------------------------------------------------------------------------------- 1 | // C# program for implementation 2 | // of Selection Sort 3 | using System; 4 | 5 | class GFG 6 | { 7 | static void sort(int []arr) 8 | { 9 | int n = arr.Length; 10 | 11 | // One by one move boundary of unsorted subarray 12 | for (int i = 0; i < n - 1; i++) 13 | { 14 | // Find the minimum element in unsorted array 15 | int min_idx = i; 16 | for (int j = i + 1; j < n; j++) 17 | if (arr[j] < arr[min_idx]) 18 | min_idx = j; 19 | 20 | // Swap the found minimum element with the first 21 | // element 22 | int temp = arr[min_idx]; 23 | arr[min_idx] = arr[i]; 24 | arr[i] = temp; 25 | } 26 | } 27 | 28 | // Prints the array 29 | static void printArray(int []arr) 30 | { 31 | int n = arr.Length; 32 | for (int i=0; i) { 19 | println("Before Sort") 20 | var A = intArrayOf(1, 7, 3, 9, 4) 21 | for (i in A) print(i) 22 | 23 | selection_sort(A) 24 | 25 | println(" 26 | Sorted array is : ") 27 | for (i in A) print(i) 28 | } 29 | -------------------------------------------------------------------------------- /Sorting/Selection Sort/selectionsort.py: -------------------------------------------------------------------------------- 1 | def selectionSort(array): 2 | n = len(array) 3 | for i in range(n): 4 | minimum = i 5 | 6 | for j in range(i+1, n): 7 | if (array[j] < array[minimum]): 8 | # Update position of minimum element if a smaller element is found. 9 | minimum = j 10 | 11 | # Swap the minimum element with the first element of the unsorted part. 12 | temp = array[i] 13 | array[i] = array[minimum] 14 | array[minimum] = temp 15 | 16 | return array 17 | 18 | # Driver code 19 | array = [13, 4, 9, 5, 3, 16, 12] 20 | print(selectionSort(array)) -------------------------------------------------------------------------------- /Sorting/Shell Sort/Shell Sorting.cpp: -------------------------------------------------------------------------------- 1 | Shell Sort 2 | 3 | #include 4 | 5 | #include 6 | 7 | void swap(int * x, int * y) { 8 | int temp = * x; 9 | * x = * y; 10 | * y = temp; 11 | } 12 | void ShellSort(int A[], int n) { 13 | int gap, i, j, temp; 14 | for (gap = n / 2; gap >= 1; gap /= 2) { 15 | for (i = gap; i < n; i++) { 16 | temp = A[i]; 17 | j = i - gap; 18 | while (j >= 0 && A[j] > temp) { 19 | A[j + gap] = A[j]; 20 | j = j - gap; 21 | } 22 | A[j + gap] = temp; 23 | } 24 | } 25 | } 26 | int main() { 27 | int A[] = {11,13,7,12,16,9,24,5,10,3}, n = 10, i; 28 | SellSort(A, n); 29 | for (i = 0; i < 10; i++) 30 | printf("%d ", A[i]); 31 | printf("\n"); 32 | return 0; 33 | } -------------------------------------------------------------------------------- /StringPrograms/Boyer Moore.cpp: -------------------------------------------------------------------------------- 1 | /* C++ Program for Bad Character Heuristic of Boyer 2 | Moore String Matching Algorithm */ 3 | #include 4 | using namespace std; 5 | # define NO_OF_CHARS 256 6 | 7 | // The preprocessing function for Boyer Moore's 8 | // bad character heuristic 9 | void badCharHeuristic( string str, int size, 10 | int badchar[NO_OF_CHARS]) 11 | { 12 | int i; 13 | 14 | // Initialize all occurrences as -1 15 | for (i = 0; i < NO_OF_CHARS; i++) 16 | badchar[i] = -1; 17 | 18 | // Fill the actual value of last occurrence 19 | // of a character 20 | for (i = 0; i < size; i++) 21 | badchar[(int) str[i]] = i; 22 | } 23 | 24 | /* A pattern searching function that uses Bad 25 | Character Heuristic of Boyer Moore Algorithm */ 26 | void search( string txt, string pat) 27 | { 28 | int m = pat.size(); 29 | int n = txt.size(); 30 | 31 | int badchar[NO_OF_CHARS]; 32 | 33 | /* Fill the bad character array by calling 34 | the preprocessing function badCharHeuristic() 35 | for given pattern */ 36 | badCharHeuristic(pat, m, badchar); 37 | 38 | int s = 0; // s is shift of the pattern with 39 | // respect to text 40 | while(s <= (n - m)) 41 | { 42 | int j = m - 1; 43 | 44 | /* Keep reducing index j of pattern while 45 | characters of pattern and text are 46 | matching at this shift s */ 47 | while(j >= 0 && pat[j] == txt[s + j]) 48 | j--; 49 | 50 | /* If the pattern is present at current 51 | shift, then index j will become -1 after 52 | the above loop */ 53 | if (j < 0) 54 | { 55 | cout << "pattern occurs at shift = " << s << endl; 56 | 57 | /* Shift the pattern so that the next 58 | character in text aligns with the last 59 | occurrence of it in pattern. 60 | The condition s+m < n is necessary for 61 | the case when pattern occurs at the end 62 | of text */ 63 | s += (s + m < n)? m-badchar[txt[s + m]] : 1; 64 | 65 | } 66 | 67 | else 68 | /* Shift the pattern so that the bad character 69 | in text aligns with the last occurrence of 70 | it in pattern. The max function is used to 71 | make sure that we get a positive shift. 72 | We may get a negative shift if the last 73 | occurrence of bad character in pattern 74 | is on the right side of the current 75 | character. */ 76 | s += max(1, j - badchar[txt[s + j]]); 77 | } 78 | } 79 | 80 | /* Driver code */ 81 | int main() 82 | { 83 | string txt= "ABAAABCD"; 84 | string pat = "ABC"; 85 | search(txt, pat); 86 | return 0; 87 | } 88 | 89 | // This code is contributed by rathbhupendra 90 | -------------------------------------------------------------------------------- /StringPrograms/Boyer Moore.py: -------------------------------------------------------------------------------- 1 | # Python3 Program for Bad Character Heuristic 2 | # of Boyer Moore String Matching Algorithm 3 | 4 | NO_OF_CHARS = 256 5 | 6 | def badCharHeuristic(string, size): 7 | ''' 8 | The preprocessing function for 9 | Boyer Moore's bad character heuristic 10 | ''' 11 | 12 | # Initialize all occurrence as -1 13 | badChar = [-1]*NO_OF_CHARS 14 | 15 | # Fill the actual value of last occurrence 16 | for i in range(size): 17 | badChar[ord(string[i])] = i; 18 | 19 | # retun initialized list 20 | return badChar 21 | 22 | def search(txt, pat): 23 | ''' 24 | A pattern searching function that uses Bad Character 25 | Heuristic of Boyer Moore Algorithm 26 | ''' 27 | m = len(pat) 28 | n = len(txt) 29 | 30 | # create the bad character list by calling 31 | # the preprocessing function badCharHeuristic() 32 | # for given pattern 33 | badChar = badCharHeuristic(pat, m) 34 | 35 | # s is shift of the pattern with respect to text 36 | s = 0 37 | while(s <= n-m): 38 | j = m-1 39 | 40 | # Keep reducing index j of pattern while 41 | # characters of pattern and text are matching 42 | # at this shift s 43 | while j>=0 and pat[j] == txt[s+j]: 44 | j -= 1 45 | 46 | # If the pattern is present at current shift, 47 | # then index j will become -1 after the above loop 48 | if j<0: 49 | print("Pattern occur at shift = {}".format(s)) 50 | 51 | ''' 52 | Shift the pattern so that the next character in text 53 | aligns with the last occurrence of it in pattern. 54 | The condition s+m < n is necessary for the case when 55 | pattern occurs at the end of text 56 | ''' 57 | s += (m-badChar[ord(txt[s+m])] if s+m15) 6 | { 7 | toHexadecimal(n/16); 8 | } 9 | if(n%16>=10) 10 | { 11 | System.out.print((char)(n%16+55)); 12 | } 13 | else 14 | { 15 | System.out.print(n%16); 16 | } 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /StringPrograms/Expression.java: -------------------------------------------------------------------------------- 1 | /* 2 | This programs converts an Arithmatic Expression in string form to 3 | integer form and solves and gives the output of Numeric Expression 4 | */ 5 | 6 | package com.company; 7 | import java.util.*; 8 | 9 | public class expression { 10 | String expn; 11 | expression() { 12 | expn = ""; 13 | } 14 | 15 | void input(String ex) { 16 | expn = ex; 17 | } 18 | 19 | public static void main(String[] args) { 20 | expression ob = new expression(); 21 | ob.input("20+7"); //String input (Arithmatic Expression) 22 | System.out.println(ob.expn); //Display Expression 23 | System.out.println(ob.getfinalval()); //Solve numeric expression to give output 24 | } 25 | 26 | long getfinalval() { 27 | String S = "+-*/"; 28 | long a, b; int p=-1; 29 | char ch; 30 | for (int i = 0; i < 4; i++) { 31 | if (expn.indexOf(S.charAt(i))>=0) 32 | p = expn.indexOf(S.charAt(i)); 33 | } 34 | if (p==-1) 35 | { 36 | System.out.println("Invalid Input"); 37 | return -999; 38 | } 39 | a = Long.parseLong(expn.substring(0, p)); 40 | b = Long.parseLong(expn.substring((p + 1))); 41 | long s = 0; 42 | ch = expn.charAt(p); 43 | switch (ch) { 44 | case '*': 45 | s = a * b; 46 | break; 47 | case '+': 48 | s = a + b; 49 | break; 50 | case '/': 51 | s = a / b; 52 | break; 53 | case '-': 54 | s = a - b; 55 | break; 56 | } 57 | return s; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /StringPrograms/FindDuplicates.java: -------------------------------------------------------------------------------- 1 | import java.io.CharConversionException; 2 | import java.util.ArrayList; 3 | 4 | public class FindDuplicates { 5 | 6 | public static void main(String[] args) { 7 | String inputString = "My name is Guarav Kukade!"; 8 | 9 | printDuplicates(inputString); 10 | } 11 | 12 | public static void printDuplicates(String inputString) { 13 | // count 14 | int count = 0; 15 | 16 | // a temp list of ch for which we have already printed the count 17 | ArrayList charList = new ArrayList<>(); 18 | 19 | for (int i = 0; i < inputString.length(); i++) { 20 | 21 | char ch = inputString.charAt(i); 22 | 23 | // count the number of occurrences of the char ch in inputString 24 | for (int j = 0; j < inputString.length(); j++) { 25 | if (inputString.charAt(j) != ch) { 26 | continue; 27 | } 28 | count++; 29 | 30 | } 31 | 32 | // check if we have already printed for ch 33 | if (!charList.contains(ch)) { 34 | // check if count is more than 1 i.e. duplicate and char should not be space 35 | if (count > 1 && ch != ' ') { 36 | 37 | System.out.println("Char: " + ch + ", Count: " + count + " times."); 38 | charList.add(ch); 39 | } 40 | } 41 | 42 | // set counter to zero for next ch 43 | count = 0; 44 | } 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /StringPrograms/KMP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | void computeLPSArray(char* pat, int M, int* lps); 4 | 5 | 6 | void KMPSearch(char* pat, char* txt) 7 | { 8 | int M = strlen(pat); 9 | int N = strlen(txt); 10 | 11 | 12 | int lps[M]; 13 | 14 | computeLPSArray(pat, M, lps); 15 | 16 | int i = 0; 17 | int j = 0; 18 | while (i < N) { 19 | if (pat[j] == txt[i]) { 20 | j++; 21 | i++; 22 | } 23 | 24 | if (j == M) { 25 | printf("Found pattern at index %d ", i - j); 26 | j = lps[j - 1]; 27 | } 28 | 29 | 30 | else if (i < N && pat[j] != txt[i]) { 31 | 32 | if (j != 0) 33 | j = lps[j - 1]; 34 | else 35 | i = i + 1; 36 | } 37 | } 38 | } 39 | 40 | 41 | void computeLPSArray(char* pat, int M, int* lps) 42 | { 43 | 44 | int len = 0; 45 | 46 | lps[0] = 0; 47 | 48 | 49 | int i = 1; 50 | while (i < M) { 51 | if (pat[i] == pat[len]) { 52 | len++; 53 | lps[i] = len; 54 | i++; 55 | } 56 | else 57 | { 58 | 59 | if (len != 0) { 60 | len = lps[len - 1]; 61 | 62 | 63 | } 64 | else 65 | { 66 | lps[i] = 0; 67 | i++; 68 | } 69 | } 70 | } 71 | } 72 | 73 | 74 | int main() 75 | { 76 | char txt[] = "ABABDABACDABABCABAB"; 77 | char pat[] = "ABABCABAB"; 78 | KMPSearch(pat, txt); 79 | return 0; 80 | } 81 | -------------------------------------------------------------------------------- /StringPrograms/Longest_Common_Subsequence.java: -------------------------------------------------------------------------------- 1 | /* A Naive recursive implementation of LCS problem in java*/ 2 | public class LongestCommonSubsequence { 3 | 4 | /* Returns length of LCS for X[0..m-1], Y[0..n-1] */ 5 | int lcs(char[] X, char[] Y, int m, int n) 6 | { 7 | if (m == 0 || n == 0) 8 | return 0; 9 | if (X[m - 1] == Y[n - 1]) 10 | return 1 + lcs(X, Y, m - 1, n - 1); 11 | else 12 | return max(lcs(X, Y, m, n - 1), lcs(X, Y, m - 1, n)); 13 | } 14 | 15 | /* Utility function to get max of 2 integers */ 16 | int max(int a, int b) 17 | { 18 | return (a > b) ? a : b; 19 | } 20 | 21 | public static void main(String[] args) 22 | { 23 | LongestCommonSubsequence lcs = new LongestCommonSubsequence(); 24 | String s1 = "AGGTAB"; 25 | String s2 = "GXTXAYB"; 26 | 27 | char[] X = s1.toCharArray(); 28 | char[] Y = s2.toCharArray(); 29 | int m = X.length; 30 | int n = Y.length; 31 | 32 | System.out.println("Length of LCS is" 33 | + " " + lcs.lcs(X, Y, m, n)); 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /StringPrograms/Longest_Common_Subsequence.py: -------------------------------------------------------------------------------- 1 | ''' 2 | Problem Statement: Given two sequences, find the length of longest subsequence present in both of them. 3 | Subsequence: subsequence is a sequence that appears in the same relative order, but not necessarily contiguous. 4 | For example, “abc”, “abg”, “bdf”, “aeg”, ‘”acefg”, .. etc are subsequences of “abcdefg”. 5 | 6 | Examples: 7 | LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3. 8 | LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4. 9 | 10 | Below is the Python implementation for the same using recursion 11 | ''' 12 | # A Naive recursive Python implementation of LCS problem 13 | 14 | def lcs(X, Y, m, n): 15 | 16 | if m == 0 or n == 0: 17 | return 0; 18 | elif X[m-1] == Y[n-1]: 19 | return 1 + lcs(X, Y, m-1, n-1); 20 | else: 21 | return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n)); 22 | 23 | 24 | # Driver program 25 | X = "AGGTAB" 26 | Y = "GXTXAYB" 27 | print "Length of LCS is ", lcs(X , Y, len(X), len(Y)) 28 | 29 | #[VIBHUTI SINGH](https://github.com/VibhuRajput) 30 | -------------------------------------------------------------------------------- /StringPrograms/Longest_common_substring.java: -------------------------------------------------------------------------------- 1 | // Java implementation of 2 | // finding length of longest 3 | // Common substring using 4 | // Dynamic Programming 5 | class GFG { 6 | /* 7 | Returns length of longest common substring 8 | of X[0..m-1] and Y[0..n-1] 9 | */ 10 | static int LCSubStr(char X[], char Y[], 11 | int m, int n) 12 | { 13 | // Create a table to store 14 | // lengths of longest common 15 | // suffixes of substrings. 16 | // Note that LCSuff[i][j] 17 | // contains length of longest 18 | // common suffix of 19 | // X[0..i-1] and Y[0..j-1]. 20 | // The first row and first 21 | // column entries have no 22 | // logical meaning, they are 23 | // used only for simplicity of program 24 | int LCStuff[][] = new int[m + 1][n + 1]; 25 | 26 | // To store length of the longest 27 | // common substring 28 | int result = 0; 29 | 30 | // Following steps build 31 | // LCSuff[m+1][n+1] in bottom up fashion 32 | for (int i = 0; i <= m; i++) 33 | { 34 | for (int j = 0; j <= n; j++) 35 | { 36 | if (i == 0 || j == 0) 37 | LCStuff[i][j] = 0; 38 | else if (X[i - 1] == Y[j - 1]) 39 | { 40 | LCStuff[i][j] 41 | = LCStuff[i - 1][j - 1] + 1; 42 | result = Integer.max(result, 43 | LCStuff[i][j]); 44 | } 45 | else 46 | LCStuff[i][j] = 0; 47 | } 48 | } 49 | return result; 50 | } 51 | 52 | // Driver Code 53 | public static void main(String[] args) 54 | { 55 | String X = "abcdabaabbacd"; 56 | String Y = "abbabaabcabcd"; 57 | 58 | int m = X.length(); 59 | int n = Y.length(); 60 | 61 | System.out.println(LCSubStr(X.toCharArray(), 62 | Y.toCharArray(), m, 63 | n)); 64 | } 65 | } 66 | 67 | -------------------------------------------------------------------------------- /StringPrograms/Pangram.java: -------------------------------------------------------------------------------- 1 | /* 2 | Check if the Sentence Is Pangram 3 | A pangram is a sentence where every letter of the English alphabet appears at least once. 4 | Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. 5 | */ 6 | 7 | class Solution { 8 | public static boolean checkIfPangram(String sentence) { 9 | String str="abcdefghijklmnopqrstuvwxyz"; 10 | for(int i=0;i True 8 | 9 | 2) Aab -> False 10 | 11 | 12 | 13 | */ 14 | 15 | 16 | import java.io.*; 17 | import java.util.*; 18 | import java.lang.Math; 19 | public class PermutationPalindrome { 20 | 21 | public static int isPermutationPalindrome(String s ) { 22 | 23 | 24 | Map hash = new HashMap<>(); 25 | 26 | for(char c: s.toCharArray()) { 27 | 28 | hash.put(c,hash.getOrDefault(c,0)+1); 29 | 30 | } 31 | int even=0; 32 | int odd =0; 33 | for(Map.Entry map : hash.entrySet()) { 34 | 35 | if(map.getValue()%2==0) { 36 | even++; 37 | } 38 | else { 39 | odd++; 40 | } 41 | 42 | } 43 | if(odd > 1) { 44 | return 0; 45 | } 46 | return 1; 47 | 48 | 49 | } 50 | public static void main (String args []) { 51 | 52 | Scanner sc = new Scanner (System.in); 53 | int t = 1; 54 | t = sc.nextInt(); 55 | sc.nextLine(); 56 | while (t > 0) { 57 | t--; 58 | String s = new String(); 59 | s = sc.next(); 60 | 61 | int flag = isPermutationPalindrome(s); 62 | if (flag == 1) { 63 | System.out.println("True"); 64 | } else { 65 | System.out.println("False"); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /StringPrograms/RabinKarp.cpp: -------------------------------------------------------------------------------- 1 | /* Following program is a C++ implementation of Rabin Karp 2 | Algorithm given in the CLRS book */ 3 | #include 4 | using namespace std; 5 | 6 | // d is the number of characters in the input alphabet 7 | #define d 256 8 | 9 | /* pat -> pattern 10 | txt -> text 11 | q -> A prime number 12 | */ 13 | void search(char pat[], char txt[], int q) 14 | { 15 | int M = strlen(pat); 16 | int N = strlen(txt); 17 | int i, j; 18 | int p = 0; // hash value for pattern 19 | int t = 0; // hash value for txt 20 | int h = 1; 21 | 22 | // The value of h would be "pow(d, M-1)%q" 23 | for (i = 0; i < M - 1; i++) 24 | h = (h * d) % q; 25 | 26 | // Calculate the hash value of pattern and first 27 | // window of text 28 | for (i = 0; i < M; i++) 29 | { 30 | p = (d * p + pat[i]) % q; 31 | t = (d * t + txt[i]) % q; 32 | } 33 | 34 | // Slide the pattern over text one by one 35 | for (i = 0; i <= N - M; i++) 36 | { 37 | 38 | // Check the hash values of current window of text 39 | // and pattern. If the hash values match then only 40 | // check for characters one by one 41 | if ( p == t ) 42 | { 43 | bool flag = true; 44 | /* Check for characters one by one */ 45 | for (j = 0; j < M; j++) 46 | { 47 | if (txt[i+j] != pat[j]) 48 | { 49 | flag = false; 50 | break; 51 | } 52 | if(flag) 53 | cout< pattern 10 | txt -> text 11 | q -> A prime number 12 | */ 13 | static void search(String pat, String txt, int q) 14 | { 15 | int M = pat.length(); 16 | int N = txt.length(); 17 | int i, j; 18 | int p = 0; // hash value for pattern 19 | int t = 0; // hash value for txt 20 | int h = 1; 21 | 22 | // The value of h would be "pow(d, M-1)%q" 23 | for (i = 0; i < M-1; i++) 24 | h = (h*d)%q; 25 | 26 | // Calculate the hash value of pattern and first 27 | // window of text 28 | for (i = 0; i < M; i++) 29 | { 30 | p = (d*p + pat.charAt(i))%q; 31 | t = (d*t + txt.charAt(i))%q; 32 | } 33 | 34 | // Slide the pattern over text one by one 35 | for (i = 0; i <= N - M; i++) 36 | { 37 | 38 | // Check the hash values of current window of text 39 | // and pattern. If the hash values match then only 40 | // check for characters on by one 41 | if ( p == t ) 42 | { 43 | /* Check for characters one by one */ 44 | for (j = 0; j < M; j++) 45 | { 46 | if (txt.charAt(i+j) != pat.charAt(j)) 47 | break; 48 | } 49 | 50 | // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] 51 | if (j == M) 52 | System.out.println("Pattern found at index " + i); 53 | } 54 | 55 | // Calculate hash value for next window of text: Remove 56 | // leading digit, add trailing digit 57 | if ( i < N-M ) 58 | { 59 | t = (d*(t - txt.charAt(i)*h) + txt.charAt(i+M))%q; 60 | 61 | // We might get negative value of t, converting it 62 | // to positive 63 | if (t < 0) 64 | t = (t + q); 65 | } 66 | } 67 | } 68 | 69 | /* Driver Code */ 70 | public static void main(String[] args) 71 | { 72 | String txt = "GEEKS FOR GEEKS"; 73 | String pat = "GEEK"; 74 | 75 | // A prime number 76 | int q = 101; 77 | 78 | // Function Call 79 | search(pat, txt, q); 80 | } 81 | } 82 | 83 | // This code is contributed by nuclode 84 | -------------------------------------------------------------------------------- /StringPrograms/RabinKarp.py: -------------------------------------------------------------------------------- 1 | # Following program is the python implementation of 2 | # Rabin Karp Algorithm given in CLRS book 3 | 4 | # d is the number of characters in the input alphabet 5 | d = 256 6 | 7 | # pat -> pattern 8 | # txt -> text 9 | # q -> A prime number 10 | 11 | def search(pat, txt, q): 12 | M = len(pat) 13 | N = len(txt) 14 | i = 0 15 | j = 0 16 | p = 0 # hash value for pattern 17 | t = 0 # hash value for txt 18 | h = 1 19 | 20 | # The value of h would be "pow(d, M-1)%q" 21 | for i in xrange(M-1): 22 | h = (h*d)%q 23 | 24 | # Calculate the hash value of pattern and first window 25 | # of text 26 | for i in xrange(M): 27 | p = (d*p + ord(pat[i]))%q 28 | t = (d*t + ord(txt[i]))%q 29 | 30 | # Slide the pattern over text one by one 31 | for i in xrange(N-M+1): 32 | # Check the hash values of current window of text and 33 | # pattern if the hash values match then only check 34 | # for characters on by one 35 | if p==t: 36 | # Check for characters one by one 37 | for j in xrange(M): 38 | if txt[i+j] != pat[j]: 39 | break 40 | else: j+=1 41 | 42 | # if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] 43 | if j==M: 44 | print "Pattern found at index " + str(i) 45 | 46 | # Calculate hash value for next window of text: Remove 47 | # leading digit, add trailing digit 48 | if i < N-M: 49 | t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%q 50 | 51 | # We might get negative values of t, converting it to 52 | # positive 53 | if t < 0: 54 | t = t+q 55 | 56 | # Driver Code 57 | txt = "GEEKS FOR GEEKS" 58 | pat = "GEEK" 59 | 60 | # A prime number 61 | q = 101 62 | 63 | # Function Call 64 | search(pat,txt,q) 65 | 66 | # This code is contributed by Bhavya Jain 67 | -------------------------------------------------------------------------------- /StringPrograms/Recursionfirstcapital.java: -------------------------------------------------------------------------------- 1 | // Recursive Approach 2 | public class FirstCapital { 3 | 4 | public static void main(String[] args) { 5 | 6 | // String str = "geekyMan"; 7 | String str = "alexAnder"; 8 | int n=0; 9 | System.out.println(firstCapital(str,n)); 10 | } 11 | 12 | static char firstCapital(String str,int n) { 13 | 14 | if(Character.isUpperCase(str.charAt(n))) { 15 | return str.charAt(n); 16 | } 17 | 18 | return firstCapital(str,n+1); 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /StringPrograms/RomanToInteger.java: -------------------------------------------------------------------------------- 1 | import java.util.HashMap; 2 | import java.util.Map; 3 | import java.util.Scanner; 4 | 5 | public class RomanToInteger { 6 | public static void main(String[] args) { 7 | Scanner kb = new Scanner(System.in); 8 | System.out.print("Enter any Roman Number: "); 9 | String roman=kb.next(); 10 | 11 | int num=romanToInt(roman); 12 | 13 | System.out.println("Integer of Roman "+roman+" is : "+num); 14 | } 15 | 16 | public static int romanToInt(String s) { 17 | Mapmap = new HashMap<>(); 18 | 19 | map.put('I',1); 20 | map.put('V',5); 21 | map.put('X',10); 22 | map.put('L',50); 23 | map.put('C',100); 24 | map.put('D',500); 25 | map.put('M',1000); 26 | 27 | int sum=0; 28 | sum+=map.get(s.charAt(0)); 29 | 30 | for(int i=1; i https://www.hackerrank.com/challenges/simple-text-editor/problem 2 | /*Implement a simple text editor. The editor initially contains an empty string S . Perform Q operations of the following 4 types: 3 | 4 | 1. append - Append string to the end of 5 | . 6 | 2. delete - Delete the last k characters of the string. 7 | 8 | 3. print - Print the kth character of string. 9 | . 10 | 4. undo - Undo the last (not previously undone) operation of type 1 or 2 , reverting S to the state it was in prior to that operation. */ 11 | 12 | 13 | #include 14 | using namespace std; 15 | 16 | 17 | int main() { 18 | //Fast Input/Output 19 | ios_base::sync_with_stdio(false); 20 | cin.tie(NULL) ; 21 | //Enter Q queries 22 | int q ; 23 | cin >> q ; 24 | // Stack to store history 25 | stack s ; 26 | 27 | //initial string 28 | string str = ""; 29 | int choice = 0 ; 30 | while(q--){ 31 | //int choice = 0 ; 32 | cin >> choice ; 33 | 34 | switch(choice){ 35 | case 1 : { s.push(str) ; 36 | string W ; 37 | cin >> W ; 38 | str.append(W) ; 39 | //cout << str << "debug" << endl ; 40 | //s.push(str) 41 | break ; 42 | } 43 | case 2 :{ s.push(str); 44 | int k ; 45 | cin >> k ; 46 | if(str.size()) 47 | str.erase(str.size() - k); 48 | //cout << str << "debug" << endl ; 49 | break ; 50 | } 51 | case 3 : { int k ; 52 | cin >> k ; 53 | if(str.size() >= k ) 54 | cout << str[k-1] << endl ; 55 | //cout << str << " " << k << "debug" << endl ; 56 | break ; 57 | } 58 | case 4 :{ str = s.top(); 59 | s.pop(); 60 | //cout << str << "debug" << endl ; 61 | break ; 62 | } 63 | default : cout << "Invalid Operation" << endl ; 64 | break ; 65 | 66 | } 67 | } 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /StringPrograms/Special Character At End.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | // Other imports go here 3 | // Do NOT change the class name 4 | 5 | /*Special Character String In a given String S, Move all special characters to the end of the String. 6 | Sample Input: 7 | Co#&de!**Quoti%%@^ent 8 | Sample Output: 9 | CodeQuotient#&!**%%@^*/ 10 | 11 | class Main 12 | { 13 | public static void main(String[] args) 14 | { 15 | // Write your code here 16 | Scanner obj = new Scanner(System.in); 17 | String s=obj.nextLine(); 18 | int l=s.length(); 19 | char arr[]=new char[l]; 20 | char a[]=new char[l]; 21 | int j=0,k=0; 22 | for(int i=0;i=65 && s.charAt(i)<92 || s.charAt(i)>=97 && s.charAt(i)<123) 25 | { 26 | arr[j]=s.charAt(i); 27 | j++; 28 | } 29 | else 30 | { 31 | a[k]=s.charAt(i); 32 | k++; 33 | } 34 | } 35 | for(int i=0;imp; 5 | for(char i:s) 6 | mp[i]++; 7 | for(char i:t) 8 | mp[i]--; 9 | for(auto it=mp.begin();it!=mp.end();it++) 10 | if(it->second!=0)return false; 11 | return true; 12 | 13 | } 14 | }; 15 | -------------------------------------------------------------------------------- /StringPrograms/Z Algorithm.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program that implements Z algorithm for pattern searching 2 | #include 3 | using namespace std; 4 | 5 | void getZarr(string str, int Z[]); 6 | 7 | // prints all occurrences of pattern in text using Z algo 8 | void search(string text, string pattern) 9 | { 10 | // Create concatenated string "P$T" 11 | string concat = pattern + "$" + text; 12 | int l = concat.length(); 13 | 14 | // Construct Z array 15 | int Z[l]; 16 | getZarr(concat, Z); 17 | 18 | // now looping through Z array for matching condition 19 | for (int i = 0; i < l; ++i) 20 | { 21 | // if Z[i] (matched region) is equal to pattern 22 | // length we got the pattern 23 | if (Z[i] == pattern.length()) 24 | cout << "Pattern found at index " 25 | << i - pattern.length() -1 << endl; 26 | } 27 | } 28 | 29 | // Fills Z array for given string str[] 30 | void getZarr(string str, int Z[]) 31 | { 32 | int n = str.length(); 33 | int L, R, k; 34 | 35 | // [L,R] make a window which matches with prefix of s 36 | L = R = 0; 37 | for (int i = 1; i < n; ++i) 38 | { 39 | // if i>R nothing matches so we will calculate. 40 | // Z[i] using naive way. 41 | if (i > R) 42 | { 43 | L = R = i; 44 | 45 | // R-L = 0 in starting, so it will start 46 | // checking from 0'th index. For example, 47 | // for "ababab" and i = 1, the value of R 48 | // remains 0 and Z[i] becomes 0. For string 49 | // "aaaaaa" and i = 1, Z[i] and R become 5 50 | while (RR nothing matches so we will calculate. 45 | // Z[i] using naive way. 46 | if(i > R){ 47 | 48 | L = R = i; 49 | 50 | // R-L = 0 in starting, so it will start 51 | // checking from 0'th index. For example, 52 | // for "ababab" and i = 1, the value of R 53 | // remains 0 and Z[i] becomes 0. For string 54 | // "aaaaaa" and i = 1, Z[i] and R become 5 55 | 56 | while(R < n && str.charAt(R - L) == str.charAt(R)) 57 | R++; 58 | 59 | Z[i] = R - L; 60 | R--; 61 | 62 | } 63 | else{ 64 | 65 | // k = i-L so k corresponds to number which 66 | // matches in [L,R] interval. 67 | int k = i - L; 68 | 69 | // if Z[k] is less than remaining interval 70 | // then Z[i] will be equal to Z[k]. 71 | // For example, str = "ababab", i = 3, R = 5 72 | // and L = 2 73 | if(Z[k] < R - i + 1) 74 | Z[i] = Z[k]; 75 | 76 | // For example str = "aaaaaa" and i = 2, R is 5, 77 | // L is 0 78 | else{ 79 | 80 | 81 | // else start from R and check manually 82 | L = i; 83 | while(R < n && str.charAt(R - L) == str.charAt(R)) 84 | R++; 85 | 86 | Z[i] = R - L; 87 | R--; 88 | } 89 | } 90 | } 91 | } 92 | 93 | // Driver program 94 | public static void main(String[] args) 95 | { 96 | String text = "GEEKS FOR GEEKS"; 97 | String pattern = "GEEK"; 98 | 99 | search(text, pattern); 100 | } 101 | } 102 | 103 | // This code is contributed by PavanKoli. 104 | -------------------------------------------------------------------------------- /StringPrograms/Z Algorithm.js: -------------------------------------------------------------------------------- 1 | 103 | -------------------------------------------------------------------------------- /StringPrograms/Z Algorithm.py: -------------------------------------------------------------------------------- 1 | # Python3 program that implements Z algorithm 2 | # for pattern searching 3 | 4 | # Fills Z array for given string str[] 5 | def getZarr(string, z): 6 | n = len(string) 7 | 8 | # [L,R] make a window which matches 9 | # with prefix of s 10 | l, r, k = 0, 0, 0 11 | for i in range(1, n): 12 | 13 | # if i>R nothing matches so we will calculate. 14 | # Z[i] using naive way. 15 | if i > r: 16 | l, r = i, i 17 | 18 | # R-L = 0 in starting, so it will start 19 | # checking from 0'th index. For example, 20 | # for "ababab" and i = 1, the value of R 21 | # remains 0 and Z[i] becomes 0. For string 22 | # "aaaaaa" and i = 1, Z[i] and R become 5 23 | while r < n and string[r - l] == string[r]: 24 | r += 1 25 | z[i] = r - l 26 | r -= 1 27 | else: 28 | 29 | # k = i-L so k corresponds to number which 30 | # matches in [L,R] interval. 31 | k = i - l 32 | 33 | # if Z[k] is less than remaining interval 34 | # then Z[i] will be equal to Z[k]. 35 | # For example, str = "ababab", i = 3, R = 5 36 | # and L = 2 37 | if z[k] < r - i + 1: 38 | z[i] = z[k] 39 | 40 | # For example str = "aaaaaa" and i = 2, 41 | # R is 5, L is 0 42 | else: 43 | 44 | # else start from R and check manually 45 | l = i 46 | while r < n and string[r - l] == string[r]: 47 | r += 1 48 | z[i] = r - l 49 | r -= 1 50 | 51 | # prints all occurrences of pattern 52 | # in text using Z algo 53 | def search(text, pattern): 54 | 55 | # Create concatenated string "P$T" 56 | concat = pattern + "$" + text 57 | l = len(concat) 58 | 59 | # Construct Z array 60 | z = [0] * l 61 | getZarr(concat, z) 62 | 63 | # now looping through Z array for matching condition 64 | for i in range(l): 65 | 66 | # if Z[i] (matched region) is equal to pattern 67 | # length we got the pattern 68 | if z[i] == len(pattern): 69 | print("Pattern found at index", 70 | i - len(pattern) - 1) 71 | 72 | # Driver Code 73 | if __name__ == "__main__": 74 | text = "GEEKS FOR GEEKS" 75 | pattern = "GEEK" 76 | search(text, pattern) 77 | 78 | # This code is contributed by 79 | # sanjeev2552 80 | -------------------------------------------------------------------------------- /StringPrograms/firstCapital.java: -------------------------------------------------------------------------------- 1 | //Linear search Approach 2 | 3 | public class FirstCapital { 4 | 5 | public static void main(String[] args) { 6 | 7 | // String str = "geekyMan"; 8 | String str = "saleSman"; 9 | char ch = firstCapital(str); 10 | System.out.println(ch); 11 | 12 | } 13 | 14 | static char firstCapital(String str) { 15 | 16 | for(int i=0;i=0;i--){ 6 | rev+=ch[i]; 7 | } 8 | return rev; 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /StringPrograms/reversestring.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | class ReverseStringForloop{ 3 | public static void main(String args[]){ 4 | String str;//declare a String variable 5 | char ch;//declare a char variable 6 | System.out.println("Enter a String as you wish: "); 7 | //ask input from the user 8 | Scanner scan=new Scanner(System.in); 9 | //cretae scanner object 10 | 11 | str =scan.nextLine(); 12 | System.out.println("Reserve of given String "+str+" is : "); 13 | for(int j=str.length(); j>0; j--){ 14 | System.out.print(str.charAt(j-1)); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /StringPrograms/string_palindrome.java: -------------------------------------------------------------------------------- 1 | class Palindrome { 2 | 3 | public static void main(String[] args) { 4 | 5 | String s = "Saas"; 6 | System.out.println(isPalindrome(s)); 7 | } 8 | 9 | static boolean isPalindrome(String s) { 10 | 11 | s = s.toLowerCase(); 12 | 13 | if(s== null || s.length()==0) { 14 | return true; 15 | } 16 | 17 | for (int i = 0; i < s.length(); i++) { 18 | 19 | char start = s.charAt(i); 20 | char end = s.charAt(s.length()-1-i); 21 | 22 | if(start!=end) { 23 | return false; 24 | } 25 | 26 | } 27 | 28 | return true; 29 | 30 | } 31 | 32 | 33 | } 34 | -------------------------------------------------------------------------------- /StringPrograms/zig_zag_string.cpp: -------------------------------------------------------------------------------- 1 | // The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) 2 | 3 | // P.......A........H.......N 4 | // ..A..P....L....S....I...I....G 5 | // ....Y.........I........R 6 | // And then read line by line: PAHNAPLSIIGYIR 7 | // Write the code that will take a string and make this conversion given a number of rows: 8 | 9 | // string convert(string text, int nRows); 10 | // convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR" 11 | // **Example 2 : ** 12 | // ABCD, 2 can be written as 13 | 14 | // A....C 15 | // ...B....D 16 | // and hence the answer would be ACBD. 17 | 18 | 19 | // Solution : 20 | 21 | #include 22 | using namespace std; 23 | 24 | string convert(string A, int B) { 25 | 26 | if(B==1) 27 | return A; 28 | if(A.length()==1) 29 | return A; 30 | string s=A; 31 | int n=A.length(); 32 | vectorv; 33 | int f=0; 34 | int jp1=((B*2)-3)-2,jp2=1; 35 | int first=((B*2)-3); 36 | for(int t=1;t<=B;t++){ 37 | 38 | if(t==1||t==B){ 39 | int j=t-1; 40 | while(j> n; 80 | cin >> s; 81 | cout << convert(s,n); 82 | 83 | } --------------------------------------------------------------------------------