├── .idea ├── .gitignore ├── Backtracking │ ├── BacktrackingAlgo.java │ └── Contributors.md ├── DIJKSTRA │ ├── Contributors.md │ └── Dijkstra.CPP ├── FILES │ ├── Contributors.md │ └── SequentialFile.C ├── HacktoberFest-Data-Structures-and-Algorithms.iml ├── PRIMS │ ├── Contributors.md │ └── Prims.CPP ├── SieveOfEratosthenes.cpp ├── Simple_calculator.py ├── TRAVERSALS │ ├── Contributors.md │ ├── Inorder to Preorder Traverse.CPP │ └── InordertoPreorder.cpp ├── aws.xml ├── codeStyles │ ├── Project.xml │ └── codeStyleConfig.xml ├── dbnavigator.xml ├── misc.xml ├── modules.xml └── vcs.xml ├── Backtracking └── nqueens.py ├── DYNAMIC PROGRAMMING ├── c or cpp │ ├── Bellman_Ford_algoritm.c │ ├── BinomialCoefficient.cpp │ ├── CatalanNumbers.cpp │ ├── Contributors.md │ ├── Edit Distance.cpp │ ├── LongestCommonSubsequence.cpp │ ├── MaxSumSubarray.cpp │ ├── minimum_cost.cpp │ └── traveling_salesman_using_dynamic_programming.c ├── java │ └── Contributors.md └── py │ ├── Contributors.md │ └── currencychange.py ├── EXPONENTIAITION BY SQUARING ├── c or cpp │ ├── Contributors.md │ ├── expo.cpp │ └── modularBinaryExponentiation.cpp ├── java │ └── Contributors.md └── py │ ├── Contributors.md │ └── ModularExponentiation.py ├── GRAPHS ├── .DS_Store ├── c or cpp │ ├── Bellman Ford.cpp │ ├── BreadthFirstSearch.cpp │ ├── Contributors.md │ ├── Graph.c │ ├── Graph.cpp │ ├── Labyrinth [0-1 Bfs , Dp].cpp │ ├── PrimsAlgo.cpp │ ├── WordLadder.cpp │ └── astar.cpp ├── java │ ├── Contributors.md │ └── dijkstra_algorithm.java └── py │ ├── Contributors.md │ └── dfs.py ├── HASHING ├── c or cpp │ ├── Contributors.md │ ├── Hash.c │ └── hashmap.cpp ├── java │ └── Contributors.md └── py │ ├── Contributors.md │ └── MD5Hashing.py ├── HEAP ├── c or cpp │ ├── Contributors.md │ ├── heap.cpp │ └── k-aryheap.cpp ├── java │ └── Contributors.md └── py │ ├── Contributors.md │ └── heap.py ├── Java Basics ├── Basics_of_java │ ├── Abstract Classes │ │ ├── App.java │ │ ├── Camera.java │ │ ├── Car.java │ │ └── Machine.java │ ├── AnonymousClasses.java │ ├── ArraysOfStrings.java │ ├── ArraysProgram.java │ ├── CastingNumericals.java │ ├── ClassesAndObjects.java │ ├── Constructors.java │ ├── DoWhileLoop.java │ ├── Encapsulation.java │ ├── Enum │ │ ├── Animal.java │ │ └── App.java │ ├── ForLoop.java │ ├── GenericsAndWildcards.java │ ├── GetterAndReturnValues.java │ ├── GettingUserInput.java │ ├── HelloWorldprogram.java │ ├── IfCondition.java │ ├── Inheritance │ │ ├── Car.java │ │ ├── IStartable.java │ │ ├── Inheritance.java │ │ └── Machine.java │ ├── InnerClasses(Nested) │ │ ├── App.java │ │ └── Robot.java │ ├── Interfaces │ │ ├── App.java │ │ ├── Info.java │ │ ├── Machine.java │ │ └── Person.java │ ├── MethodParameters.java │ ├── MethodsInClasses.java │ ├── MultiDimensionalArrays.java │ ├── MultipleExceptions │ │ ├── App.java │ │ └── Test.java │ ├── Packages │ │ ├── Algae.java │ │ ├── App.java │ │ ├── Fish.java │ │ └── Seaweed.java │ ├── PassingByValue │ │ ├── App.java │ │ └── Person.java │ ├── Polymorphism │ │ ├── App.java │ │ ├── Plant.java │ │ └── Tree.java │ ├── Public,Private,Protected │ │ ├── App.java │ │ ├── Field.java │ │ ├── Grass.java │ │ ├── Oak.java │ │ └── Plant.java │ ├── ReadingFiles.java │ ├── ReadingFileswithFileReader.java │ ├── Recursion.java │ ├── RuntimeExceptions.java │ ├── Serialization │ │ ├── Person.java │ │ ├── ReadObjects.java │ │ └── WriteObjects.java │ ├── SetterAndThis.java │ ├── StaticAndFinal.java │ ├── StringBuilderAndStringFormatting.java │ ├── SwitchCase.java │ ├── ToStringMethods.java │ ├── TryWithResources │ │ ├── App.java │ │ └── App2.java │ ├── UpcastingAndDowncasting.java │ ├── UsingGenerics.java │ ├── UsingStrings.java │ ├── UsingVariables.java │ ├── WhileLoop.java │ └── WritingTextFiles.java └── README.md.txt ├── LINKED LIST ├── c or cpp │ ├── CircularLinkedList.cpp │ ├── Contributors.md │ ├── DLL.cpp │ ├── Doubly_Circular_Linked_List.c │ ├── Doubly_linked_list.cpp │ ├── Intersection.c │ ├── LinkListUsingSTL.CPP │ ├── Merge_Sort.c │ ├── Palindrome_Linked_list.cpp │ ├── Remove_Duplicates.c │ ├── SinglyLinkedList.cpp │ ├── Skiplist.cpp │ ├── Sparse_Matrix_creation.c │ ├── Unions.c │ ├── dll.h │ └── sorting linked list.c ├── java │ ├── Contributors.md │ ├── Sorting │ │ ├── MergeSort.java │ │ ├── MergeSort.md │ │ └── Sort-Linked-List-768x384.png │ └── linkedlist.java └── py │ ├── Contributors.md │ ├── LinkedList.py │ └── is_palindrome.py ├── OBJECT ORIENTED PROGRAMMING ├── c or cpp │ ├── Contributors.md │ ├── Herarchical_inheritance │ │ ├── Herarchical_inheritance.cbp │ │ ├── Herarchical_inheritance.layout │ │ ├── bin │ │ │ └── Debug │ │ │ │ └── Herarchical_inheritance.exe │ │ ├── main.cpp │ │ └── obj │ │ │ └── Debug │ │ │ └── main.o │ ├── Hybrid_Inheritance │ │ ├── Hybrid_Inheritance.cbp │ │ ├── Hybrid_Inheritance.depend │ │ ├── Hybrid_Inheritance.layout │ │ ├── bin │ │ │ └── Debug │ │ │ │ └── Hybrid_Inheritance.exe │ │ ├── main.cpp │ │ └── obj │ │ │ └── Debug │ │ │ └── main.o │ └── friendfunction.cpp ├── java │ └── Contributors.md └── py │ ├── Contributors.md │ └── hierarchial inheritance with an example.txt ├── PATTERNS ├── halfpyramid.c ├── pascalTriangle.cpp └── pattern.c ├── PRIMALITY TESTING ALGORITHMS ├── c or cpp │ ├── Contributors.md │ └── sieve.cpp ├── java │ └── Contributors.md └── py │ └── Contributors.md ├── README.md ├── RECURSION ├── c or cpp │ ├── Contributors.md │ ├── Factorial.cpp │ ├── Greatest_Common_Divisor.cpp │ ├── Multiplication.c │ └── sum_of_square_of_binomial_coeffiecient │ │ ├── readme.md │ │ └── sum_of_square_of_binomial_coefficient.cpp ├── java │ ├── Contributors.md │ ├── NumberOfPaths.java │ ├── all_subset_of_string.java │ └── factorial.java └── py │ ├── Contributors.md │ ├── Factorial.py │ ├── Fibonacci_Sequence.py │ └── palindrome.py ├── SEARCHING ├── c or cpp │ ├── Contributors.md │ ├── Divide_&_conquer_to_find_min_&_max.c │ ├── binarySearch.cpp │ └── linear_search.cpp ├── java │ ├── Contributors.md │ ├── binary_search.java │ └── linear_search.java └── py │ ├── Binary_search.py │ ├── Contributors.md │ ├── binary_search.py │ ├── jumpsearch.py │ └── linea_search.py ├── SORTING ├── c or cpp │ ├── Contributors.md │ ├── Different_Sorts.c │ ├── MergeSort.cpp │ ├── QuickSort.cpp │ ├── RadixSort.cpp │ ├── bubblesort.cpp │ ├── insertion_sort.cpp │ └── selection_sort.cpp ├── countingsort.cpp ├── java │ ├── BubbleSort.java │ ├── Contributors.md │ ├── HeapSort.java │ └── InsertionSort.java └── py │ ├── 3-way quick sort .py │ ├── BillCalculation.py │ ├── Bubble Sort.py │ ├── Contributors.md │ ├── HeapSort.py │ ├── MergeSort.py │ ├── QuickSort.py │ ├── SelectionSort.py │ ├── kahn_topological_sort.py │ └── pybogo.py ├── STACK AND QUEUES ├── c or cpp │ ├── COE19B046_Infix.c │ ├── COE19B046_list.h │ ├── Contributors.md │ ├── Evaluate_Postfix.cpp │ ├── Queue_ADT.c │ ├── Stack.h │ ├── Stack_ADT.c │ ├── Stack_Operations.cpp │ └── stack.cpp ├── java │ ├── Contributors.md │ └── Stack.java └── py │ ├── Contributors.md │ ├── __pycache__ │ └── queue.cpython-39.pyc │ ├── infixtopostfix.py │ └── queue.py ├── STRINGS ├── c or cpp │ ├── Contributors.md │ ├── Palindrome.c │ ├── encodestring.cpp │ └── matrix_calculator.cpp ├── java │ └── Contributors.md └── py │ ├── Change case.py │ ├── Contributors.md │ ├── StringFormatting.py │ ├── domain.py │ ├── first_non_repeating.py │ └── reverse_words.py ├── TREES ├── c or cpp │ ├── AVL.CPP │ ├── BinarySearchTree.cpp │ ├── BinaryTree.CPP │ ├── BtreePerformingRecursiveTraversal.CPP │ ├── Contributors.md │ ├── ExpressionTree.cpp │ ├── MWayTree.CPP │ ├── OBST.CPP │ ├── ThreadedBinaryTree.cpp │ ├── Tree.c │ ├── bstFromSortedArr.cpp │ ├── postorder.cpp │ ├── tree.cpp │ └── treePreIn.cpp ├── java │ └── Contributors.md ├── py │ └── Contributors.md └── treePreIn.cpp └── bstFromSortedArr.cpp /.idea/.gitignore: -------------------------------------------------------------------------------- 1 | # Default ignored files 2 | /shelf/ 3 | /workspace.xml 4 | # Datasource local storage ignored files 5 | /dataSources/ 6 | /dataSources.local.xml 7 | # Zeppelin ignored files 8 | /ZeppelinRemoteNotebooks/ 9 | # Editor-based HTTP Client requests 10 | /httpRequests/ 11 | -------------------------------------------------------------------------------- /.idea/Backtracking/Contributors.md: -------------------------------------------------------------------------------- 1 | If you have contributed to this repository, kindly add your username here 2 | 3 | - [Dhruvil Shah](https://github.com/d-s-2803) 4 | - [Gaurav Verma](https://github.com/thegauravverma) 5 | - [Mayank Pandey](https://github.com/Mayshank18) 6 | -------------------------------------------------------------------------------- /.idea/DIJKSTRA/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 6 | -------------------------------------------------------------------------------- /.idea/FILES/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Mayur Narkhede](https://github.com/PrinceMayur007) -------------------------------------------------------------------------------- /.idea/HacktoberFest-Data-Structures-and-Algorithms.iml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/PRIMS/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 6 | -------------------------------------------------------------------------------- /.idea/SieveOfEratosthenes.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | void SieveOfEratosthenes(int n) 4 | { 5 | bool prime[n+1]; 6 | memset(prime, true, sizeof(prime)); 7 | 8 | for (int p=2; p*p<=n; p++) 9 | { 10 | if (prime[p] == true) 11 | { 12 | for (int i=p*p; i<=n; i += p) 13 | prime[i] = false; 14 | } 15 | } 16 | for (int p=2; p<=n; p++) 17 | if (prime[p]) 18 | cout << p << " "; 19 | } 20 | int main() 21 | { 22 | int n ; 23 | cout << "Enter the number" << endl ; 24 | cin >> n ; 25 | cout << "Following are the prime numbers smaller " 26 | << " than or equal to " << n << endl; 27 | SieveOfEratosthenes(n); 28 | return 0; 29 | } 30 | 31 | 32 | /* 33 | Enter the number 5 34 | Following are the prime numbers smaller than or equal to 5 35 | 2 3 5 36 | */ -------------------------------------------------------------------------------- /.idea/Simple_calculator.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | #Simple Calculator using Tkinter in Python 3 | 4 | def click(event): 5 | global scrval 6 | text = event.widget.cget("text") 7 | if text == "=": 8 | if scrval.get().isdigit(): 9 | value = int(scrval.get()) 10 | else: 11 | value = eval(screen.get()) 12 | scrval.set(value) 13 | 14 | elif text == "C": 15 | scrval.set("") 16 | screen.update() 17 | else: 18 | scrval.set(scrval.get() + text) 19 | screen.update() 20 | 21 | 22 | root=Tk() 23 | root.geometry("500x550") 24 | root.title("GUI Simple Calculator") 25 | 26 | scrval = StringVar() 27 | scrval.set("") 28 | 29 | screen = Entry(root, textvar=scrval, font="lucida 30 bold", bd=4,relief=SUNKEN) 30 | screen.pack() 31 | 32 | frame = Frame(root, bg="grey", pady=10) 33 | list1 = ["7", "8", "9", "C", "4", "5", "6", "+", "1", "2", "3", "-" ,".", "0", "=", "*", "%", "!", "^", "/"] 34 | i = 0 35 | for n in list1: 36 | # here width of button means 1 text width 37 | btn = Button(frame, text=n, font="lucida 20 bold", padx=50, width =1,pady=25 ) 38 | btn.grid(row=int(i / 4), column=i % 4) 39 | i = i + 1 40 | 41 | btn.bind("", click) 42 | frame.pack(fill=X) 43 | 44 | root.mainloop() 45 | -------------------------------------------------------------------------------- /.idea/TRAVERSALS/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 6 | -------------------------------------------------------------------------------- /.idea/aws.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | -------------------------------------------------------------------------------- /.idea/codeStyles/Project.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 20 | 21 | 22 | 23 | 29 | 30 | 31 | 32 | 33 | 39 | 40 | 44 | 45 | 46 | 48 | 49 | -------------------------------------------------------------------------------- /.idea/codeStyles/codeStyleConfig.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /.idea/vcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /Backtracking/nqueens.py: -------------------------------------------------------------------------------- 1 | class Solution(object): 2 | def solveNQueens(self, n): 3 | """ 4 | :type n: int 5 | :rtype: List[List[str]] 6 | """ 7 | # recusive 8 | if n == 0: 9 | return 0 10 | res = [] 11 | board = [['.'] * n for t in range(n)] 12 | self.do_solveNQueens(res, board, n) 13 | return res 14 | 15 | def do_solveNQueens(self, res, board, num): 16 | if num == 0: 17 | res.append([''.join(t) for t in board]) 18 | return 19 | ls = len(board) 20 | pos = ls - num 21 | check = [True] * ls 22 | for i in range(pos): 23 | for j in range(ls): 24 | if board[i][j] == 'Q': 25 | check[j] = False 26 | step = pos - i 27 | if j + step < ls: 28 | check[j + step] = False 29 | if j - step >= 0: 30 | check[j - step] = False 31 | break 32 | for j in range(ls): 33 | if check[j]: 34 | board[pos][j] = 'Q' 35 | self.do_solveNQueens(res, board, num - 1) 36 | board[pos][j] = '.' 37 | 38 | 39 | if __name__ == '__main__': 40 | # begin 41 | s = Solution() 42 | print s.solveNQueens(4) -------------------------------------------------------------------------------- /DYNAMIC PROGRAMMING/c or cpp/BinomialCoefficient.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int nCk(int n, int k) 5 | { 6 | int C[k+1]; 7 | memset(C, 0, sizeof(C)); 8 | C[0] = 1; // Base case 9 | 10 | for (int i = 1; i <= n; i++) 11 | { // iteratively build the coefficient 12 | for (int j = min(i, k); j > 0; j--) C[j] = C[j] + C[j-1]; 13 | } 14 | return C[k]; 15 | } 16 | 17 | int main() 18 | { 19 | int n = 5, k = 2; 20 | cout << "Value of C[" << n << "][" 21 | << k << "] is " << nCk(n, k); 22 | } 23 | -------------------------------------------------------------------------------- /DYNAMIC PROGRAMMING/c or cpp/CatalanNumbers.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | unsigned long int catalanDP(unsigned int n) 5 | { 6 | unsigned long int catalan[n+1]; 7 | 8 | catalan[0] = catalan[1] = 1; 9 | 10 | for (int i=2; i<=n; i++) 11 | { 12 | catalan[i] = 0; 13 | for (int j=0; j 2 | #include 3 | 4 | using std::string; 5 | 6 | int edit_distance(const string &str1, const string &str2) { 7 | using namespace std; 8 | int strl1 = str1.size(); 9 | int strl2 = str2.size(); 10 | 11 | int dMatrix[strl1][strl2]; 12 | 13 | for(int i=0;i> str1 >> str2; 43 | std::cout << edit_distance(str1, str2) << std::endl; 44 | return 0; 45 | } 46 | -------------------------------------------------------------------------------- /DYNAMIC PROGRAMMING/c or cpp/LongestCommonSubsequence.cpp: -------------------------------------------------------------------------------- 1 | // Refer to the complete problem statement here: https://practice.geeksforgeeks.org/problems/longest-common-subsequence/0 2 | 3 | #include 4 | using namespace std; 5 | 6 | int lcs(string s1, string s2){ 7 | int n1=s1.size(),n2=s2.size(); 8 | int dp[n1+1][n2+1]; 9 | for(int i=0;i<=n1;i++){ 10 | for(int j=0;j<=n2;j++){ 11 | if(i==0 || j==0) 12 | dp[i][j] = 0; 13 | else{ 14 | dp[i][j] = max(dp[i-1][j],dp[i][j-1]); 15 | if(s1[i-1]==s2[j-1]) 16 | dp[i][j] = max(dp[i][j], 1+dp[i-1][j-1]); 17 | } 18 | } 19 | } 20 | int res = dp[n1][n2]; 21 | } 22 | 23 | int main() 24 | { 25 | int T; 26 | cout<<"Enter number of test cases: "; 27 | cin>>T; 28 | cout<>n1>>n2; 33 | cout<>s1>>s2; 37 | cout< 2 | 3 | using namespace std; 4 | 5 | int max(int a, int b){ 6 | int m; 7 | m= (a>b)?a:b; 8 | return m; 9 | } 10 | int main() 11 | { 12 | //int N=6; 13 | //int arr[]={1,2,3,4,5,6}; 14 | int N; 15 | int m; 16 | //m=4; 17 | cout<<"Enter number of elements: "; 18 | cin>>N; 19 | int arr[N]; 20 | cout<<"\nEnter elements of array: "; 21 | for(int i=0;i>arr[i]; 23 | } 24 | cout<<"\nEnter subarray size: "; 25 | cin>>m; 26 | int i=0,j=0,sum=0,Max=-1; 27 | while(j 5 | using namespace std; 6 | 7 | int main() { 8 | int m, n; 9 | cout << "Please enter row and column size.\n"; 10 | cin >> m >> n ; 11 | int a[m][n]; 12 | cout << "Please enter elements.\n"; 13 | for(int i = 0; i < m ;i++){ 14 | for(int j = 0; j < n; j++) 15 | cin >> a[i][j]; 16 | } 17 | // storing sum across 1st row 18 | for(int i = 1; i < n; i++) 19 | a[0][i] += a[0][i - 1]; 20 | // stoing sum across 1st column 21 | for(int i = 1; i < m; i++) 22 | a[i][0] += a[i - 1][0]; 23 | for(int i = 1; i < m; i++){ 24 | for(int j = 1; j < n; j++){ 25 | // taking minimum cost by taking min of left, top and top-left element 26 | a[i][j] += ( min(a[i - 1][j], min( a[i][j - 1], a[i - 1][j - 1] ) ) ); 27 | } 28 | } 29 | // value at destination 30 | cout << "Minimum cost : " << a[m-1][n-1] << endl; 31 | return 0; 32 | } 33 | 34 | // Time Complexity : O(mn) 35 | // This is because we use nested loops of m and n to iterate over the original matrix 36 | // to calculate minimum cost. 37 | 38 | // Auxililary Space Complexity : O(1) -------------------------------------------------------------------------------- /DYNAMIC PROGRAMMING/c or cpp/traveling_salesman_using_dynamic_programming.c: -------------------------------------------------------------------------------- 1 | #include 2 | int a[10][10],completed[10],n,cost=0; 3 | void mincost(int city); 4 | int minValue(int c); 5 | int main() 6 | { 7 | int i,j; 8 | printf("Enter the number of villages: "); 9 | scanf("%d",&n); 10 | printf("\nEnter the Cost Matrix (%dX%d):\n",n,n); 11 | for(i=0;i 5 | using namespace std; 6 | 7 | #define N 1000000007 // prime modulo value 8 | 9 | long int exponentiation(long int base, 10 | long int exp) 11 | { 12 | if (exp == 0) 13 | return 1; 14 | 15 | if (exp == 1) 16 | return base % N; 17 | 18 | long int t = exponentiation(base, exp / 2); 19 | t = (t * t) % N; 20 | 21 | // if exponent is even value 22 | if (exp % 2 == 0) 23 | return t; 24 | 25 | // if exponent is odd value 26 | else 27 | return ((base % N) * t) % N; 28 | } 29 | 30 | // Driver Code 31 | int main() 32 | { 33 | long int base; 34 | long int exp; 35 | cin>>base>>exp; 36 | 37 | long int modulo = exponentiation(base, exp); 38 | cout << modulo << endl; 39 | return 0; 40 | } 41 | 42 | -------------------------------------------------------------------------------- /EXPONENTIAITION BY SQUARING/c or cpp/modularBinaryExponentiation.cpp: -------------------------------------------------------------------------------- 1 | #include "bits/stdc++.h" 2 | #define ll long long 3 | #define lld long double 4 | #define MOD 1000000007 5 | #define inf 1000000000000000000ll 6 | #define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 7 | 8 | ll power(ll x,ll y, ll md=inf) { 9 | ll res = 1;x%=md; 10 | while(y){ 11 | if(y&1) 12 | res = (res*x)%md; 13 | x *= x; 14 | if(x>=md) 15 | x %= md; 16 | y >>= 1; 17 | } 18 | return res; 19 | } 20 | 21 | int main(){ 22 | assert(power(3,5)==243); 23 | assert(power(2,15)==32768); 24 | } 25 | -------------------------------------------------------------------------------- /EXPONENTIAITION BY SQUARING/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /EXPONENTIAITION BY SQUARING/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Yasasvi V Peruvemba](https://github.com/YasasviPeruvemba) 8 | -------------------------------------------------------------------------------- /EXPONENTIAITION BY SQUARING/py/ModularExponentiation.py: -------------------------------------------------------------------------------- 1 | def power(a, b, mod): 2 | res = 1 3 | while (b > 0): 4 | if b%2: # if it is not divisible by 2 5 | res = ((res%mod)*(a%mod))%mod 6 | b = int(b/2) 7 | a = ((a%mod)*(a%mod))%mod 8 | return res 9 | 10 | assert (power(5,2,1000000007) == 25) 11 | assert (power(3,7,1000000007) == 2187) 12 | -------------------------------------------------------------------------------- /GRAPHS/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/GRAPHS/.DS_Store -------------------------------------------------------------------------------- /GRAPHS/c or cpp/Bellman Ford.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std ; 4 | 5 | struct Edge { 6 | int src, dest, weight; 7 | }; 8 | 9 | struct Graph { 10 | int V, E; 11 | struct Edge* edge; 12 | }; 13 | 14 | struct Graph* createGraph(int V, int E) 15 | { 16 | struct Graph* graph = new Graph; 17 | graph->V = V; 18 | graph->E = E; 19 | graph->edge = new Edge[E]; 20 | return graph; 21 | } 22 | 23 | void printArr(int dist[], int n) 24 | { 25 | printf("Vertex Distance from Source\n"); 26 | for (int i = 0; i < n; ++i) 27 | printf("%d \t\t %d\n", i, dist[i]); 28 | } 29 | 30 | void BellmanFord(struct Graph* graph, int src) 31 | { 32 | int V = graph->V; 33 | int E = graph->E; 34 | int dist[V]; 35 | 36 | for (int i = 0; i < V; i++) 37 | dist[i] = INT_MAX; 38 | dist[src] = 0; 39 | 40 | for (int i = 1; i <= V - 1; i++) { 41 | for (int j = 0; j < E; j++) { 42 | int u = graph->edge[j].src; 43 | int v = graph->edge[j].dest; 44 | int weight = graph->edge[j].weight; 45 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) 46 | dist[v] = dist[u] + weight; 47 | } 48 | } 49 | 50 | for (int i = 0; i < E; i++) { 51 | int u = graph->edge[i].src; 52 | int v = graph->edge[i].dest; 53 | int weight = graph->edge[i].weight; 54 | if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) { 55 | printf("Graph contains negative weight cycle"); 56 | return; 57 | } 58 | } 59 | 60 | printArr(dist, V); 61 | 62 | return; 63 | } 64 | 65 | int main() 66 | { 67 | int V ; 68 | cout<<"Enter no. of vertices : " ; 69 | cin>>V ; 70 | 71 | int E ; 72 | cout<<"Enter no. of edges : " ; 73 | cin>>E ; 74 | 75 | struct Graph* graph = createGraph(V, E); 76 | 77 | for(int i=0;i>graph->edge[i].src>>graph->edge[i].dest>>graph->edge[i].weight ; 80 | } 81 | 82 | BellmanFord(graph, 0); 83 | 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /GRAPHS/c or cpp/BreadthFirstSearch.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Queue{ 5 | public : 6 | int size,Queue[100],i = 0,nice,j; 7 | int front = -1; 8 | int rear = -1; 9 | 10 | void readQueue(int n) 11 | { 12 | size = n; 13 | } 14 | 15 | void enqueue(int element) 16 | { 17 | Queue[i] = element; 18 | i++; 19 | rear++; 20 | } 21 | 22 | int Dequeue(){ 23 | if(front < rear){ 24 | front++; 25 | return Queue[front]; 26 | } 27 | } 28 | 29 | void display(){ 30 | cout<<"\n"; 31 | if(front == rear){ 32 | cout<<"Queue is empty"; 33 | } 34 | else{ 35 | for(j = front + 1 ; j <= rear ; j++){ 36 | cout<>G[i][j]; 62 | } 63 | } 64 | } 65 | 66 | void BFS(int f , int n , Queue Q){ 67 | int path[50],current,i,j=0; 68 | int visited[n] ={0}; 69 | visited[f] = 1; 70 | Q.enqueue(f); 71 | path[j] = f; 72 | j++; 73 | 74 | while(!Q.isEmpty()){ 75 | current = Q.Dequeue(); 76 | for(i = 0 ; i < n ; i++){ 77 | if(G[current][i] == 1 && visited[i] == 0){ 78 | visited[i] = 1; 79 | Q.enqueue(i); 80 | path[j] = i; 81 | j++; 82 | } 83 | } 84 | } 85 | cout<<"\n"; 86 | cout<<"The BSF path is ->"; 87 | for(i = 0 ; i < j ; i++){ 88 | cout<<"-->"<>n; 101 | G.readGraph(n); 102 | cout<<"\n"; 103 | cout<<"Enter the node you want to start search from"; 104 | cin>>node; 105 | G.BFS(node , n ,Q); 106 | } 107 | 108 | /* 109 | Enter no of vertices6 110 | 0 1 0 0 1 0 111 | 1 0 1 1 1 0 112 | 0 1 0 1 0 1 113 | 0 1 1 0 1 1 114 | 1 1 0 1 0 1 115 | 0 0 1 1 1 0 116 | 117 | Enter the node you want to start search from :- 0 118 | 119 | The BSF path is ->-->0-->1-->4-->2-->3-->5 120 | */ 121 | -------------------------------------------------------------------------------- /GRAPHS/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Varun Irani](https://github.com/VarunIrani) 8 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 9 | - [Atharva Kulkarni](https://github.com/AK9175) 10 | -------------------------------------------------------------------------------- /GRAPHS/c or cpp/Graph.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/GRAPHS/c or cpp/Graph.cpp -------------------------------------------------------------------------------- /GRAPHS/c or cpp/PrimsAlgo.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int n,i,j,m=2,cost=0; 5 | printf("Enter no of vertices you need"); 6 | scanf("%d",&n); 7 | printf("\n"); 8 | printf("Enter 9999 if no edge exist"); 9 | printf("\n"); 10 | int G[n][n]; 11 | for(i = 0 ; i < n ; i++) 12 | { 13 | for(j = 0 ; j < n ; j++) 14 | { 15 | scanf("%d",&G[i][j]); 16 | } 17 | } 18 | 19 | int u,v,min=999; 20 | for(i = 0 ; i < n ; i++) 21 | { 22 | for(j = i ; j < n ; j++) 23 | { 24 | if(G[i][j] < min) 25 | { 26 | min = G[i][j]; 27 | u = i; 28 | v = j; 29 | } 30 | } 31 | } 32 | 33 | cost = cost + G[u][v]; 34 | 35 | int visited[n] = {0}; 36 | int value[100]; 37 | value[0] = u; 38 | value[1] = v; 39 | visited[u] = 1; 40 | visited[v] = 1; 41 | printf("\n"); 42 | 43 | for(int z = 1 ; z <= n-2 ; z++) 44 | { 45 | min = 999; 46 | for(i = 0 ; i < n ; i++) 47 | { 48 | for(j = 0 ; j < n ; j++) 49 | { 50 | if(visited[i] != 1 && visited[j] == 1) 51 | { 52 | if(G[i][j] < min) 53 | { 54 | min = G[i][j]; 55 | u = j; 56 | v = i; 57 | } 58 | } 59 | } 60 | } 61 | visited[u] = 1; 62 | visited[v] = 1; 63 | value[m] = u; 64 | m++; 65 | value[m] = v; 66 | m++; 67 | cost = cost + G[u][v]; 68 | } 69 | 70 | printf("Prims way is : -"); 71 | printf("\n"); 72 | printf("\n"); 73 | int t=1; 74 | for(i = 0 ; i < m ; i++) 75 | { 76 | printf("%d --> ",value[i]); 77 | if(t >= 2) 78 | { 79 | printf("\n"); 80 | t = 0; 81 | } 82 | t++; 83 | } 84 | 85 | printf("\n"); 86 | 87 | printf("Minimum cost of the spnning tree is :- %d",cost); 88 | 89 | } 90 | -------------------------------------------------------------------------------- /GRAPHS/c or cpp/WordLadder.cpp: -------------------------------------------------------------------------------- 1 | // https://leetcode.com/problems/word-ladder/ 2 | 3 | bool dist(string a, string b){ 4 | int count=0; 5 | for(int i=0;i& wordList) { 14 | if(find(wordList.begin(),wordList.end(),endWord)==wordList.end()) 15 | return 0; 16 | if(beginWord==endWord) return 1; 17 | 18 | if(dist(beginWord,endWord)) return 2; 19 | 20 | int n=wordList.size(); 21 | vector visit(n,false); 22 | queue > q; 23 | 24 | q.push(make_pair(1,beginWord)); 25 | while(!q.empty()){ 26 | 27 | pair pos=q.front(); 28 | q.pop(); 29 | int level=pos.first; 30 | if(dist(pos.second,endWord)) return pos.first+1; 31 | level++; 32 | for(int i=0;i 2 | #include 3 | voidmain() 4 | { 5 | int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; 6 | int n, value; 7 | int temp, hash; 8 | clrscr(); 9 | printf("\nEnter the value of n(table size):");scanf("%d", &n); 10 | do 11 | { 12 | printf("\nEnter the hash value"); 13 | scanf("%d", &value); 14 | hash = value % n; 15 | if(a[hash] == 0) 16 | { 17 | a[hash] = value; 18 | printf("\na[%d]the value %d is stored", hash, value); 19 | } 20 | else 21 | { 22 | for(hash++; hash < n; hash++) 23 | { 24 | if(a[hash] == 0) 25 | { 26 | printf("Space is allocated give other value");a[hash] = value; 27 | printf("\n a[%d]the value %d is stored", hash, value); 28 | gotomenu; 29 | } 30 | } 31 | for(hash = 0; hash < n; hash++) 32 | { 33 | if(a[hash] == 0) 34 | { 35 | printf("Space is allocated give other value");a[hash] = value; 36 | printf("\n a[%d]the value %d is stored", hash, value); 37 | gotomenu; 38 | } 39 | } 40 | printf("\n\nERROR\n"); 41 | printf("\nEnter '0' and press 'Enter key' twice to exit"); 42 | } 43 | menu: 44 | printf("\n Do u want enter more"); 45 | scanf("%d", &temp); 46 | }while(temp == 1); 47 | getch(); 48 | } -------------------------------------------------------------------------------- /HASHING/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /HASHING/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Vivek Ray](https://github.com/vivekray903) 8 | 9 | -------------------------------------------------------------------------------- /HASHING/py/MD5Hashing.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # Python code to generate MD5 hashing and check their similarity based on Hash 3 | 4 | import hashlib # Supports hashing functions 5 | 6 | message1= str(input("Enter message 1 =")) 7 | message2= str(input("Enter message 2 =")) 8 | 9 | encoding1 = message1.encode() 10 | encoding2 = message2.encode() 11 | 12 | hash1 = (hashlib.md5(encoding1)).hexdigest() 13 | hash2 = (hashlib.md5(encoding2)).hexdigest() 14 | 15 | # Printing the hash in hexadecimal format 16 | print("The byte equivalent of hash for message 1 is : ", hash1) 17 | 18 | # Printing the hash in hexadecimal format 19 | print("The byte equivalent of hash for message 2 is : ", hash2) 20 | 21 | if hash1 == hash2 : 22 | print("The message are similar.") 23 | else: 24 | print("The message are different.") 25 | -------------------------------------------------------------------------------- /HEAP/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /HEAP/c or cpp/heap.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for implementation 2 | // of Iterative Heap Sort 3 | #include 4 | using namespace std; 5 | 6 | // function build Max Heap where value 7 | // of each child is always smaller 8 | // than value of their parent 9 | void buildMaxHeap(int arr[], int n) 10 | { 11 | for (int i = 1; i < n; i++) 12 | { 13 | // if child is bigger than parent 14 | if (arr[i] > arr[(i - 1) / 2]) 15 | { 16 | int j = i; 17 | 18 | // swap child and parent until 19 | // parent is smaller 20 | while (arr[j] > arr[(j - 1) / 2]) 21 | { 22 | swap(arr[j], arr[(j - 1) / 2]); 23 | j = (j - 1) / 2; 24 | } 25 | } 26 | } 27 | } 28 | 29 | void heapSort(int arr[], int n) 30 | { 31 | buildMaxHeap(arr, n); 32 | 33 | for (int i = n - 1; i > 0; i--) 34 | { 35 | // swap value of first indexed 36 | // with last indexed 37 | swap(arr[0], arr[i]); 38 | 39 | // maintaining heap property 40 | // after each swapping 41 | int j = 0, index; 42 | 43 | do 44 | { 45 | index = (2 * j + 1); 46 | 47 | // if left child is smaller than 48 | // right child point index variable 49 | // to right child 50 | if (arr[index] < arr[index + 1] && 51 | index < (i - 1)) 52 | index++; 53 | 54 | // if parent is smaller than child 55 | // then swapping parent with child 56 | // having higher value 57 | if (arr[j] < arr[index] && index < i) 58 | swap(arr[j], arr[index]); 59 | 60 | j = index; 61 | 62 | } while (index < i); 63 | } 64 | } 65 | 66 | // Driver Code to test above 67 | int main() 68 | { 69 | int arr[] = {10, 20, 15, 17, 9, 21}; 70 | int n = sizeof(arr) / sizeof(arr[0]); 71 | 72 | printf("Given array: "); 73 | for (int i = 0; i < n; i++) 74 | printf("%d ", arr[i]); 75 | 76 | printf("\n\n"); 77 | 78 | heapSort(arr, n); 79 | 80 | // print array after sorting 81 | printf("Sorted array: "); 82 | for (int i = 0; i < n; i++) 83 | printf("%d ", arr[i]); 84 | 85 | return 0; 86 | } -------------------------------------------------------------------------------- /HEAP/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /HEAP/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Abhishek kumar](https://github.com/avik001) 8 | -------------------------------------------------------------------------------- /HEAP/py/heap.py: -------------------------------------------------------------------------------- 1 | class BinaryHeap(object): 2 | def __init__(self): 3 | self.heap = [0] 4 | self.currentSize = 0 5 | 6 | def __repr__(self): 7 | heap = self.heap[1:] 8 | return ' '.join(str(i) for i in heap) 9 | 10 | # for shifting the node up 11 | def shiftUp(self, index): 12 | while (index // 2) > 0: 13 | if self.heap[index] < self.heap[index // 2]: # (currentSize // 2) is the parent 14 | temp = self.heap[index // 2] 15 | self.heap[index // 2] = self.heap[index] 16 | self.heap[index] = temp 17 | index = index // 2 18 | 19 | # to insert a node in the heap 20 | def insert(self, key): 21 | self.heap.append(key) 22 | self.currentSize += 1 23 | self.shiftUp(self.currentSize) 24 | 25 | # for shifting down a node 26 | def shiftDown(self, index): 27 | while(index * 2) <= self.currentSize: 28 | minimumChild = self.minChild(index) 29 | if self.heap[index] > self.heap[minimumChild]: 30 | temp = self.heap[index] 31 | self.heap[index] = self.heap[minimumChild] 32 | self.heap[minimumChild] = temp 33 | index = minimumChild 34 | 35 | # for finding the child with minimum value 36 | def minChild(self,i): 37 | if i * 2 + 1 > self.currentSize: 38 | return i * 2 39 | else: 40 | if self.heap[i * 2] < self.heap[i * 2 + 1]: 41 | return i * 2 42 | else: 43 | return i * 2 + 1 44 | 45 | # for deleting a node from the heap and maintaining the heap property 46 | def delete(self): 47 | deletedNode = self.heap[1] 48 | self.heap[1] = self.heap[self.currentSize] 49 | self.currentSize -= 1 50 | self.heap.pop() 51 | self.shiftDown(1) 52 | return deletedNode 53 | 54 | # for building heap 55 | def buildHeap(self, alist): 56 | i = len(alist) // 2 57 | self.currentSize = len(alist) 58 | self.heap = [0] + alist[:] 59 | while (i > 0): 60 | self.shiftDown(i) 61 | i = i - 1 62 | 63 | bh = BinaryHeap() 64 | bh.buildHeap([9,5,6,2,3]) 65 | 66 | print('Deleted:', bh.delete()) 67 | print('Deleted:', bh.delete()) 68 | print('Deleted:', bh.delete()) 69 | bh.insert(3) 70 | print('Deleted:', bh.delete()) 71 | print(bh) -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Abstract Classes/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | Camera cam1 = new Camera(); 5 | cam1.setId(5); 6 | 7 | Car car1 = new Car(); 8 | car1.setId(4); 9 | 10 | car1.run(); 11 | 12 | //Machine machine1 = new Machine(); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Abstract Classes/Camera.java: -------------------------------------------------------------------------------- 1 | public class Camera extends Machine { 2 | 3 | @Override 4 | public void start() { 5 | System.out.println("Starting camera."); 6 | } 7 | 8 | @Override 9 | public void doStuff() { 10 | System.out.println("Taking a photo"); 11 | 12 | } 13 | 14 | @Override 15 | public void shutdown() { 16 | System.out.println("Shutting down the camera."); 17 | 18 | } 19 | 20 | } 21 | 22 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Abstract Classes/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Machine { 2 | 3 | @Override 4 | public void start() { 5 | System.out.println("Starting ignition..."); 6 | 7 | } 8 | 9 | @Override 10 | public void doStuff() { 11 | System.out.println("Driving..."); 12 | } 13 | 14 | @Override 15 | public void shutdown() { 16 | System.out.println("Switch off ignition."); 17 | 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Abstract Classes/Machine.java: -------------------------------------------------------------------------------- 1 | public abstract class Machine { 2 | private int id; 3 | 4 | public int getId() { 5 | return id; 6 | } 7 | 8 | public void setId(int id) { 9 | this.id = id; 10 | } 11 | 12 | public abstract void start(); 13 | public abstract void doStuff(); 14 | public abstract void shutdown(); 15 | 16 | public void run() { 17 | start(); 18 | doStuff(); 19 | shutdown(); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/AnonymousClasses.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | public void start() { 3 | System.out.println("Starting machine ..."); 4 | } 5 | } 6 | 7 | interface Plant { 8 | public void grow(); 9 | } 10 | 11 | public class AnonymousClasses { 12 | 13 | public static void main(String[] args) { 14 | 15 | // This is equivalent to creating a class that "extends" 16 | // Machine and overrides the start method. 17 | Machine machine1 = new Machine() { 18 | @Override public void start() { 19 | System.out.println("Camera snapping ...."); 20 | } 21 | }; 22 | 23 | machine1.start(); 24 | 25 | // This is equivalent to creating a class that "implements" 26 | // the Plant interface 27 | Plant plant1 = new Plant() { 28 | @Override 29 | public void grow() { 30 | System.out.println("Plant growing"); 31 | 32 | } 33 | }; 34 | 35 | plant1.grow(); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ArraysOfStrings.java: -------------------------------------------------------------------------------- 1 | public class ArraysOfStrings { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | // Declare array of (references to) strings. 7 | String[] words = new String[3]; 8 | 9 | // Set the array elements (point the references 10 | // at strings) 11 | words[0] = "Hello"; 12 | words[1] = "to"; 13 | words[2] = "you"; 14 | 15 | // Access an array element and print it. 16 | System.out.println(words[2]); 17 | 18 | // Simultaneously declare and initialize an array of strings 19 | String[] fruits = {"apple", "banana", "pear", "kiwi"}; 20 | 21 | // Iterate through an array 22 | for(String fruit: fruits) { 23 | System.out.println(fruit); 24 | } 25 | 26 | // "Default" value for an integer 27 | int value = 0; 28 | 29 | // Default value for a reference is "null" 30 | String text = null; 31 | 32 | System.out.println(text); 33 | 34 | // Declare an array of strings 35 | String[] texts = new String[2]; 36 | 37 | // The references to strings in the array 38 | // are initialized to null. 39 | System.out.println(texts[0]); 40 | 41 | // ... But of course we can set them to actual strings. 42 | texts[0] = "one"; 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ArraysProgram.java: -------------------------------------------------------------------------------- 1 | public class ArraysProgram { 2 | public static void main(String[] args) { 3 | 4 | int value = 7; 5 | 6 | int[] values; 7 | values = new int[3]; 8 | 9 | System.out.println(values[0]); 10 | 11 | values[0] = 10; 12 | values[1] = 20; 13 | values[2] = 30; 14 | 15 | System.out.println(values[0]); 16 | System.out.println(values[1]); 17 | System.out.println(values[2]); 18 | 19 | for(int i=0; i < values.length; i++) { 20 | System.out.println(values[i]); 21 | } 22 | 23 | int[] numbers = {5, 6, 7}; 24 | 25 | for(int i=0; i < numbers.length; i++) { 26 | System.out.println(numbers[i]); 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/CastingNumericals.java: -------------------------------------------------------------------------------- 1 | public class CastingNumericals { 2 | 3 | /** 4 | * @param args 5 | */ 6 | public static void main(String[] args) { 7 | 8 | byte byteValue = 20; 9 | short shortValue = 55; 10 | int intValue = 888; 11 | long longValue = 23355; 12 | 13 | float floatValue = 8834.8f; 14 | float floatValue2 = (float)99.3; 15 | double doubleValue = 32.4; 16 | 17 | System.out.println(Byte.MAX_VALUE); 18 | 19 | intValue = (int)longValue; 20 | 21 | System.out.println(intValue); 22 | 23 | doubleValue = intValue; 24 | System.out.println(doubleValue); 25 | 26 | intValue = (int)floatValue; 27 | System.out.println(intValue); 28 | 29 | 30 | // The following won't work as we expect it to!! 31 | // 128 is too big for a byte. 32 | byteValue = (byte)128; 33 | System.out.println(byteValue); 34 | 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ClassesAndObjects.java: -------------------------------------------------------------------------------- 1 | 2 | class Person { 3 | 4 | // Instance variables (data or "state") 5 | String name; 6 | int age; 7 | 8 | 9 | // Classes can contain 10 | 11 | // 1. Data 12 | // 2. Subroutines (methods) 13 | } 14 | 15 | 16 | public class ClassesAndObjects{ 17 | 18 | public static void main(String[] args) { 19 | 20 | 21 | // Create a Person object using the Person class 22 | Person person1 = new Person(); 23 | person1.name = "Joe Bloggs"; 24 | person1.age = 37; 25 | 26 | // Create a second Person object 27 | Person person2 = new Person(); 28 | person2.name = "Sarah Smith"; 29 | person2.age = 20; 30 | 31 | System.out.println(person1.name); 32 | 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Constructors.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | private String name; 3 | private int code; 4 | 5 | public Machine() { 6 | this("Arnie", 0); 7 | 8 | System.out.println("Constructor running!"); 9 | } 10 | 11 | public Machine(String name) { 12 | this(name, 0); 13 | 14 | System.out.println("Second constructor running"); 15 | // No longer need following line, since we're using the other constructor above. 16 | //this.name = name; 17 | } 18 | 19 | public Machine(String name, int code) { 20 | 21 | System.out.println("Third constructor running"); 22 | this.name = name; 23 | this.code = code; 24 | } 25 | } 26 | 27 | public class Constructors { 28 | public static void main(String[] args) { 29 | Machine machine1 = new Machine(); 30 | 31 | Machine machine2 = new Machine("Bertie"); 32 | 33 | Machine machine3 = new Machine("Chalky", 7); 34 | } 35 | 36 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/DoWhileLoop.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | 4 | public class DoWhileLoop { 5 | 6 | public static void main(String[] args) { 7 | 8 | 9 | Scanner scanner = new Scanner(System.in); 10 | 11 | 12 | System.out.println("Enter a number: "); 13 | int value = scanner.nextInt(); 14 | 15 | while(value != 5) { 16 | System.out.println("Enter a number: "); 17 | value = scanner.nextInt(); 18 | } 19 | 20 | 21 | int value = 0; 22 | do { 23 | System.out.println("Enter a number: "); 24 | value = scanner.nextInt(); 25 | } 26 | while(value != 5); 27 | 28 | System.out.println("Got 5!"); 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Encapsulation.java: -------------------------------------------------------------------------------- 1 | class Plant { 2 | 3 | // Usually only static final members are public 4 | public static final int ID = 7; 5 | 6 | // Instance variables should be declared private, 7 | // or at least protected. 8 | private String name; 9 | 10 | // Only methods intended for use outside the class 11 | // should be public. These methods should be documented 12 | // carefully if you distribute your code. 13 | public String getData() { 14 | String data = "some stuff" + calculateGrowthForecast(); 15 | 16 | return data; 17 | } 18 | 19 | // Methods only used the the class itself should 20 | // be private or protected. 21 | private int calculateGrowthForecast() { 22 | return 9; 23 | } 24 | 25 | 26 | public String getName() { 27 | return name; 28 | } 29 | 30 | public void setName(String name) { 31 | this.name = name; 32 | } 33 | 34 | 35 | } 36 | 37 | 38 | public class Encapsulation { 39 | 40 | public static void main(String[] args) { 41 | 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Enum/Animal.java: -------------------------------------------------------------------------------- 1 | public enum Animal { 2 | CAT("Fergus"), DOG("Fido"), MOUSE("Jerry"); 3 | 4 | private String name; 5 | 6 | Animal(String name) { 7 | this.name = name; 8 | } 9 | 10 | public String getName() { 11 | return name; 12 | } 13 | 14 | public String toString() { 15 | return "This animal is called: " + name; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Enum/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | Animal animal = Animal.DOG; 6 | 7 | switch(animal) { 8 | case CAT: 9 | System.out.println("Cat"); 10 | break; 11 | case DOG: 12 | System.out.println("Dog"); 13 | break; 14 | case MOUSE: 15 | break; 16 | default: 17 | break; 18 | 19 | } 20 | 21 | System.out.println(Animal.DOG); 22 | System.out.println("Enum name as a string: " + Animal.DOG.name()); 23 | 24 | System.out.println(Animal.DOG.getClass()); 25 | 26 | System.out.println(Animal.DOG instanceof Enum); 27 | 28 | System.out.println(Animal.MOUSE.getName()); 29 | 30 | Animal animal2 = Animal.valueOf("CAT"); 31 | 32 | System.out.println(animal2); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ForLoop.java: -------------------------------------------------------------------------------- 1 | public class ForLoop { 2 | public static void main(String[] args) { 3 | 4 | for(int i=0; i < 5; i++) { 5 | System.out.printf("The value of i is: %dn", i); 6 | } 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/GenericsAndWildcards.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | 3 | class Machine { 4 | 5 | @Override 6 | public String toString() { 7 | return "I am a machine"; 8 | } 9 | 10 | public void start() { 11 | System.out.println("Machine starting."); 12 | } 13 | 14 | } 15 | 16 | class Camera extends Machine { 17 | @Override 18 | public String toString() { 19 | return "I am a camera"; 20 | } 21 | 22 | public void snap() { 23 | System.out.println("snap!"); 24 | } 25 | } 26 | 27 | public class App { 28 | 29 | public static void main(String[] args) { 30 | 31 | ArrayList list1 = new ArrayList(); 32 | 33 | list1.add(new Machine()); 34 | list1.add(new Machine()); 35 | 36 | ArrayList list2 = new ArrayList(); 37 | 38 | list2.add(new Camera()); 39 | list2.add(new Camera()); 40 | 41 | showList(list2); 42 | showList2(list1); 43 | showList3(list1); 44 | } 45 | 46 | public static void showList(ArrayList list) { 47 | for (Machine value : list) { 48 | System.out.println(value); 49 | value.start(); 50 | } 51 | 52 | } 53 | 54 | public static void showList2(ArrayList list) { 55 | for (Object value : list) { 56 | System.out.println(value); 57 | } 58 | } 59 | 60 | public static void showList3(ArrayList list) { 61 | for (Object value : list) { 62 | System.out.println(value); 63 | } 64 | } 65 | 66 | 67 | } 68 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/GetterAndReturnValues.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | String name; 3 | int age; 4 | 5 | void speak() { 6 | System.out.println("My name is: " + name); 7 | } 8 | 9 | int calculateYearsToRetirement() { 10 | int yearsLeft = 65 - age; 11 | 12 | return yearsLeft; 13 | } 14 | 15 | int getAge() { 16 | return age; 17 | } 18 | 19 | String getName() { 20 | return name; 21 | } 22 | } 23 | 24 | 25 | public class GetterAndReturnValues { 26 | 27 | public static void main(String[] args) { 28 | Person person1 = new Person(); 29 | 30 | person1.name = "Joe"; 31 | person1.age = 25; 32 | 33 | // person1.speak(); 34 | 35 | int years = person1.calculateYearsToRetirement(); 36 | 37 | System.out.println("Years till retirements " + years); 38 | 39 | int age = person1.getAge(); 40 | String name = person1.getName(); 41 | 42 | System.out.println("Name is: " + name); 43 | System.out.println("Age is: " + age); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/GettingUserInput.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class GettingUserInput { 4 | public static void main(String[] args) { 5 | 6 | // Creating scanner object 7 | Scanner input = new Scanner(System.in); 8 | 9 | // Output the prompt 10 | System.out.println("Enter a floating point value: "); 11 | 12 | // enter something. 13 | double value = input.nextDouble(); 14 | 15 | //they entered. 16 | System.out.println("You entered: " + value); 17 | } 18 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/HelloWorldprogram.java: -------------------------------------------------------------------------------- 1 | public class HelloWorldprogram 2 | { 3 | 4 | public static void main(String[] args) { 5 | System.out.println("Hello World!"); 6 | } 7 | 8 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/IfCondition.java: -------------------------------------------------------------------------------- 1 | public class IfCondition 2 | { 3 | public static void main(String[] args) { 4 | 5 | // Some useful conditions: 6 | System.out.println(5 == 5); 7 | System.out.println(10 != 11); 8 | System.out.println(3 < 6); 9 | System.out.println(10 > 100); 10 | 11 | // Using loops with "break": 12 | int loop = 0; 13 | 14 | while(true) { 15 | System.out.println("Looping: " + loop); 16 | 17 | if(loop == 3) { 18 | break; 19 | } 20 | 21 | loop++; 22 | 23 | System.out.println("Running"); 24 | } 25 | } 26 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Inheritance/Car.java: -------------------------------------------------------------------------------- 1 | public class Car extends Machine { 2 | 3 | 4 | @Override 5 | public void start() { 6 | System.out.println("Car started"); 7 | } 8 | 9 | public void wipeWindShield() { 10 | System.out.println("Wiping windshield"); 11 | } 12 | 13 | public void showInfo() { 14 | System.out.println("Car name: " + name); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Inheritance/IStartable.java: -------------------------------------------------------------------------------- 1 | public interface IStartable { 2 | public void start(); 3 | public void stop(); 4 | } 5 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Inheritance/Inheritance.java: -------------------------------------------------------------------------------- 1 | public class Inheritance { 2 | 3 | public static void main(String[] args) { 4 | Machine mach1 = new Machine(); 5 | 6 | mach1.start(); 7 | mach1.stop(); 8 | 9 | Car car1 = new Car(); 10 | 11 | car1.start(); 12 | car1.wipeWindShield(); 13 | car1.showInfo(); 14 | car1.stop(); 15 | 16 | 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Inheritance/Machine.java: -------------------------------------------------------------------------------- 1 | public class Machine { 2 | 3 | protected String name = "Machine Type 1"; 4 | 5 | public void start() { 6 | System.out.println("Machine started."); 7 | } 8 | 9 | public void stop() { 10 | System.out.println("Machine stopped."); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/InnerClasses(Nested)/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | Robot robot = new Robot(7); 7 | robot.start(); 8 | 9 | // The syntax below will only work if Brain is 10 | // declared public. It is quite unusual to do this. 11 | // Robot.Brain brain = robot.new Brain(); 12 | // brain.think(); 13 | 14 | // This is very typical Java syntax, using 15 | // a static inner class. 16 | Robot.Battery battery = new Robot.Battery(); 17 | battery.charge(); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/InnerClasses(Nested)/Robot.java: -------------------------------------------------------------------------------- 1 | public class Robot { 2 | 3 | private int id; 4 | 5 | // Non-static nested classes have access to the enclosing 6 | // class's instance data. E.g. implement Iterable 7 | // http://www.caveofprogramming.com/java/using-iterable-java-collections-framework-video-tutorial-part-11/ 8 | // Use them to group functionality. 9 | private class Brain { 10 | public void think() { 11 | System.out.println("Robot " + id + " is thinking."); 12 | } 13 | } 14 | 15 | // static inner classes do not have access to instance data. 16 | // They are really just like "normal" classes, except that they are grouped 17 | // within an outer class. Use them for grouping classes together. 18 | public static class Battery { 19 | public void charge() { 20 | System.out.println("Battery charging..."); 21 | } 22 | } 23 | 24 | public Robot(int id) { 25 | this.id = id; 26 | } 27 | 28 | public void start() { 29 | System.out.println("Starting robot " + id); 30 | 31 | // Use Brain. We don't have an instance of brain 32 | // until we create one. Instances of brain are 33 | // always associated with instances of Robot (the 34 | // enclosing class). 35 | Brain brain = new Brain(); 36 | brain.think(); 37 | 38 | final String name = "Robert"; 39 | 40 | // Sometimes it's useful to create local classes 41 | // within methods. You can use them only within the method. 42 | class Temp { 43 | public void doSomething() { 44 | System.out.println("ID is: " + id); 45 | System.out.println("My name is " + name); 46 | } 47 | } 48 | 49 | Temp temp = new Temp(); 50 | temp.doSomething(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Interfaces/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | Machine mach1 = new Machine(); 6 | mach1.start(); 7 | 8 | Person person1 = new Person("Bob"); 9 | person1.greet(); 10 | 11 | Info info1 = new Machine(); 12 | info1.showInfo(); 13 | 14 | Info info2 = person1; 15 | info2.showInfo(); 16 | 17 | System.out.println(); 18 | 19 | outputInfo(mach1); 20 | outputInfo(person1); 21 | } 22 | 23 | private static void outputInfo(Info info) { 24 | info.showInfo(); 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Interfaces/Info.java: -------------------------------------------------------------------------------- 1 | 2 | public interface Info { 3 | public void showInfo(); 4 | } 5 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Interfaces/Machine.java: -------------------------------------------------------------------------------- 1 | public class Machine implements Info { 2 | 3 | private int id = 7; 4 | 5 | public void start() { 6 | System.out.println("Machine started."); 7 | } 8 | 9 | public void showInfo() { 10 | System.out.println("Machine ID is: " + id); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Interfaces/Person.java: -------------------------------------------------------------------------------- 1 | public class Person implements Info { 2 | 3 | private String name; 4 | 5 | public Person(String name) { 6 | this.name = name; 7 | } 8 | 9 | public void greet() { 10 | System.out.println("Hello there."); 11 | } 12 | 13 | @Override 14 | public void showInfo() { 15 | System.out.println("Person name is: " + name); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/MethodParameters.java: -------------------------------------------------------------------------------- 1 | class Robot { 2 | public void speak(String text) { 3 | System.out.println(text); 4 | } 5 | 6 | public void jump(int height) { 7 | System.out.println("Jumping: " + height); 8 | } 9 | 10 | public void move(String direction, double distance) { 11 | System.out.println("Moving " + distance + " in direction " + direction); 12 | } 13 | } 14 | 15 | public class MethodParameters { 16 | 17 | public static void main(String[] args) { 18 | Robot sam = new Robot(); 19 | 20 | sam.speak("Hi I'm Sam"); 21 | sam.jump(7); 22 | 23 | sam.move("West", 12.2); 24 | 25 | String greeting = "Hello there"; 26 | sam.speak(greeting); 27 | 28 | int value = 14; 29 | sam.jump(value); 30 | 31 | } 32 | 33 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/MethodsInClasses.java: -------------------------------------------------------------------------------- 1 | class Person { 2 | 3 | // Instance variables (data or "state") 4 | String name; 5 | int age; 6 | 7 | // Classes can contain 8 | 9 | // 1. Data 10 | // 2. Subroutines (methods) 11 | 12 | void speak() { 13 | for(int i=0; i<3; i++) { 14 | System.out.println("My name is: " + name + " and I am " + age + " years old "); 15 | } 16 | } 17 | 18 | void sayHello() { 19 | System.out.println("Hello there!"); 20 | } 21 | } 22 | 23 | public class MethodsInClasses { 24 | 25 | public static void main(String[] args) { 26 | 27 | // Create a Person object using the Person class 28 | Person person1 = new Person(); 29 | person1.name = "Joe Bloggs"; 30 | person1.age = 37; 31 | person1.speak(); 32 | person1.sayHello(); 33 | 34 | // Create a second Person object 35 | Person person2 = new Person(); 36 | person2.name = "Sarah Smith"; 37 | person2.age = 20; 38 | person2.speak(); 39 | person1.sayHello(); 40 | 41 | System.out.println(person1.name); 42 | 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/MultiDimensionalArrays.java: -------------------------------------------------------------------------------- 1 | public class MultiDimensionalArrays { 2 | 3 | public static void main(String[] args) { 4 | 5 | 6 | int[] values = {3, 5, 2343}; 7 | 8 | 9 | System.out.println(values[2]); 10 | 11 | 12 | int[][] grid = { 13 | {3, 5, 2343}, 14 | {2, 4}, 15 | {1, 2, 3, 4} 16 | }; 17 | 18 | 19 | System.out.println(grid[1][1]); 20 | System.out.println(grid[0][2]); 21 | 22 | 23 | String[][] texts = new String[2][3]; 24 | 25 | texts[0][1] = "Hello there"; 26 | 27 | System.out.println(texts[0][1]); 28 | 29 | 30 | for(int row=0; row < grid.length; row++) { 31 | for(int col=0; col < grid[row].length; col++) { 32 | System.out.print(grid[row][col] + "\t"); 33 | } 34 | 35 | System.out.println(); 36 | } 37 | 38 | 39 | String[][] words = new String[2][]; 40 | 41 | 42 | System.out.println(words[0]); 43 | 44 | 45 | words[0] = new String[3]; 46 | 47 | 48 | words[0][1] = "hi there"; 49 | 50 | System.out.println(words[0][1]); 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/MultipleExceptions/App.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.IOException; 3 | import java.text.ParseException; 4 | 5 | public class App { 6 | 7 | public static void main(String[] args) { 8 | Test test = new Test(); 9 | 10 | // Multiple catch blocks 11 | try { 12 | test.run(); 13 | } catch (IOException e) { 14 | // TODO Auto-generated catch block 15 | e.printStackTrace(); 16 | } catch (ParseException e) { 17 | System.out.println("Couldn't parse command file."); 18 | } 19 | 20 | // Try multi-catch (Java 7+ only) 21 | try { 22 | test.run(); 23 | } catch (IOException | ParseException e) { 24 | // TODO Auto-generated catch block 25 | e.printStackTrace(); 26 | } 27 | 28 | // Using polymorphism to catch the parent of all exceptions 29 | try { 30 | test.run(); 31 | } catch (Exception e) { 32 | // TODO Auto-generated catch block 33 | e.printStackTrace(); 34 | } 35 | 36 | // Important to catch exceptions in the right order! 37 | // IOException cannot come first, because it's the parent 38 | // of FileNotFoundException, so would catch both exceptions 39 | // in this case. 40 | try { 41 | test.input(); 42 | } catch (FileNotFoundException e) { 43 | // TODO Auto-generated catch block 44 | e.printStackTrace(); 45 | } catch (IOException e) { 46 | // TODO Auto-generated catch block 47 | e.printStackTrace(); 48 | } 49 | 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/MultipleExceptions/Test.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.IOException; 3 | import java.text.ParseException; 4 | 5 | 6 | public class Test { 7 | public void run() throws IOException, ParseException { 8 | 9 | 10 | //throw new IOException(); 11 | 12 | throw new ParseException("Error in command list.", 2); 13 | 14 | 15 | } 16 | 17 | public void input() throws IOException, FileNotFoundException { 18 | 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Packages/Algae.java: -------------------------------------------------------------------------------- 1 | package ocean.plants; 2 | 3 | public class Algae { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Packages/App.java: -------------------------------------------------------------------------------- 1 | import ocean.Fish; 2 | import ocean.plants.Seaweed; 3 | 4 | public class App { 5 | 6 | 7 | public static void main(String[] args) { 8 | Fish fish = new Fish(); 9 | Seaweed weed = new Seaweed(); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Packages/Fish.java: -------------------------------------------------------------------------------- 1 | package ocean; 2 | 3 | public class Fish { 4 | 5 | } 6 | 7 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Packages/Seaweed.java: -------------------------------------------------------------------------------- 1 | package ocean.plants; 2 | 3 | public class Seaweed { 4 | 5 | } 6 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/PassingByValue/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | 4 | public static void main(String[] args) { 5 | App app = new App(); 6 | 7 | //=========================================== 8 | 9 | int value = 7; 10 | System.out.println("1. Value is: " + value); 11 | 12 | app.show(value); 13 | 14 | System.out.println("4. Value is: " + value); 15 | 16 | //=========================================== 17 | System.out.println(); 18 | 19 | Person person = new Person("Bob"); 20 | System.out.println("1. Person is: " + person); 21 | 22 | app.show(person); 23 | 24 | System.out.println("4. Person is: " + person); 25 | } 26 | 27 | public void show(int value) { 28 | System.out.println("2. Value is: " + value); 29 | 30 | value = 8; 31 | 32 | System.out.println("3. Value is: " + value); 33 | } 34 | 35 | public void show(Person person) { 36 | System.out.println("2. Person is: " + person); 37 | 38 | 39 | 40 | person = new Person("Mike"); 41 | person.setName("Sue"); 42 | 43 | System.out.println("3. Person is: " + person); 44 | 45 | } 46 | 47 | 48 | } 49 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/PassingByValue/Person.java: -------------------------------------------------------------------------------- 1 | public class Person { 2 | private String name; 3 | 4 | public Person(String name) { 5 | this.name = name; 6 | } 7 | 8 | public String getName() { 9 | return name; 10 | } 11 | 12 | public void setName(String name) { 13 | this.name = name; 14 | } 15 | 16 | @Override 17 | public String toString() { 18 | return "Person [name=" + name + "]"; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Polymorphism/App.java: -------------------------------------------------------------------------------- 1 | public class App { 2 | 3 | public static void main(String[] args) { 4 | 5 | 6 | Plant plant1 = new Plant(); 7 | 8 | // Tree is a kind of Plant (it extends Plant) 9 | Tree tree = new Tree(); 10 | 11 | // Polymorphism guarantees that we can use a child class 12 | // wherever a parent class is expected. 13 | Plant plant2 = tree; 14 | 15 | // plant2 references a Tree, so the Tree grow() method is called. 16 | plant2.grow(); 17 | 18 | // The type of the reference decided what methods you can actually call; 19 | // we need a Tree-type reference to call tree-specific methods. 20 | tree.shedLeaves(); 21 | 22 | // ... so this won't work. 23 | //plant2.shedLeaves(); 24 | 25 | // Another example of polymorphism. 26 | doGrow(tree); 27 | } 28 | 29 | public static void doGrow(Plant plant) { 30 | plant.grow(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Polymorphism/Plant.java: -------------------------------------------------------------------------------- 1 | public class Plant { 2 | public void grow() { 3 | System.out.println("Plant growing"); 4 | } 5 | } 6 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Polymorphism/Tree.java: -------------------------------------------------------------------------------- 1 | public class Tree extends Plant { 2 | 3 | @Override 4 | public void grow() { 5 | System.out.println("Tree growing"); 6 | } 7 | 8 | public void shedLeaves() { 9 | System.out.println("Leaves shedding."); 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Public,Private,Protected/App.java: -------------------------------------------------------------------------------- 1 | import world.Plant; 2 | 3 | /* 4 | * private --- only within same class 5 | * public --- from anywhere 6 | * protected -- same class, subclass, and same package 7 | * no modifier -- same package only 8 | */ 9 | 10 | public class App { 11 | 12 | public static void main(String[] args) { 13 | Plant plant = new Plant(); 14 | 15 | System.out.println(plant.name); 16 | 17 | System.out.println(plant.ID); 18 | 19 | // Won't work --- type is private 20 | //System.out.println(plant.type); 21 | 22 | // size is protected; App is not in the same package as Plant. 23 | // Won't work 24 | // System.out.println(plant.size); 25 | 26 | // Won't work; App and Plant in different packages, height has package-level visibility. 27 | //System.out.println(plant.height); 28 | 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Public,Private,Protected/Field.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | public class Field { 4 | private Plant plant = new Plant(); 5 | 6 | public Field() { 7 | 8 | // size is protected; Field is in the same package as Plant. 9 | System.out.println(plant.size); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Public,Private,Protected/Grass.java: -------------------------------------------------------------------------------- 1 | import world.Plant; 2 | 3 | 4 | public class Grass extends Plant { 5 | public Grass() { 6 | 7 | // Won't work --- Grass not in same package as plant, even though it's a subclass 8 | // System.out.println(this.height); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Public,Private,Protected/Oak.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | public class Oak extends Plant { 4 | 5 | public Oak() { 6 | 7 | // Won't work -- type is private 8 | // type = "tree"; 9 | 10 | // This works --- size is protected, Oak is a subclass of plant. 11 | this.size = "large"; 12 | 13 | // No access specifier; works because Oak and Plant in same package 14 | this.height = 10; 15 | } 16 | 17 | } 18 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Public,Private,Protected/Plant.java: -------------------------------------------------------------------------------- 1 | package world; 2 | 3 | class Something { 4 | 5 | } 6 | 7 | public class Plant { 8 | // Bad practice 9 | public String name; 10 | 11 | // Accepetable practice --- it's final. 12 | public final static int ID = 8; 13 | 14 | private String type; 15 | 16 | protected String size; 17 | 18 | int height; 19 | 20 | public Plant() { 21 | this.name = "Freddy"; 22 | this.type = "plant"; 23 | this.size = "medium"; 24 | this.height = 8; 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ReadingFiles.java: -------------------------------------------------------------------------------- 1 | import java.io.File; 2 | import java.io.FileNotFoundException; 3 | import java.util.Scanner; 4 | 5 | 6 | public class ReadingFiles { 7 | 8 | public static void main(String[] args) throws FileNotFoundException { 9 | //String fileName = "C:/Users/John/Desktop/example.txt"; 10 | String fileName = "example.txt"; 11 | 12 | File textFile = new File(fileName); 13 | 14 | Scanner in = new Scanner(textFile); 15 | 16 | int value = in.nextInt(); 17 | System.out.println("Read value: " + value); 18 | 19 | in.nextLine(); 20 | 21 | int count = 2; 22 | while(in.hasNextLine()) { 23 | String line = in.nextLine(); 24 | 25 | System.out.println(count + ": " + line); 26 | count++; 27 | } 28 | 29 | in.close(); 30 | } 31 | 32 | } 33 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ReadingFileswithFileReader.java: -------------------------------------------------------------------------------- 1 | 2 | import java.io.BufferedReader; 3 | import java.io.File; 4 | import java.io.FileNotFoundException; 5 | import java.io.FileReader; 6 | import java.io.IOException; 7 | 8 | 9 | public class ReadingFileswithFileReader{ 10 | 11 | public static void main(String[] args) { 12 | 13 | File file = new File("test.txt"); 14 | 15 | BufferedReader br = null; 16 | 17 | try { 18 | FileReader fr = new FileReader(file); 19 | br = new BufferedReader(fr); 20 | 21 | String line; 22 | 23 | while( (line = br.readLine()) != null ) { 24 | System.out.println(line); 25 | } 26 | 27 | } catch (FileNotFoundException e) { 28 | System.out.println("File not found: " + file.toString()); 29 | } catch (IOException e) { 30 | System.out.println("Unable to read file: " + file.toString()); 31 | } 32 | finally { 33 | try { 34 | br.close(); 35 | } catch (IOException e) { 36 | System.out.println("Unable to close file: " + file.toString()); 37 | } 38 | catch(NullPointerException ex) { 39 | // File was probably never opened! 40 | } 41 | } 42 | 43 | 44 | 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Recursion.java: -------------------------------------------------------------------------------- 1 | public class Recursion { 2 | 3 | 4 | public static void main(String[] args) { 5 | 6 | // E.g. 4! = 4*3*2*1 (factorial 4) 7 | 8 | System.out.println(factorial(5)); 9 | } 10 | 11 | private static int factorial(int value) { 12 | //System.out.println(value); 13 | 14 | if(value == 1) { 15 | return 1; 16 | } 17 | 18 | return factorial(value - 1) * value; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/RuntimeExceptions.java: -------------------------------------------------------------------------------- 1 | public class RuntimeExceptions { 2 | 3 | public static void main(String[] args) { 4 | 5 | // Null pointer exception .... 6 | String text = null; 7 | 8 | System.out.println(text.length()); 9 | 10 | // Arithmetic exception ... (divide by zero) 11 | int value = 7/0; 12 | 13 | // You can actually handle RuntimeExceptions if you want to; 14 | // for example, here we handle an ArrayIndexOutOfBoundsException 15 | String[] texts = { "one", "two", "three" }; 16 | 17 | try { 18 | System.out.println(texts[3]); 19 | } catch (ArrayIndexOutOfBoundsException e) { 20 | System.out.println(e.toString()); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Serialization/Person.java: -------------------------------------------------------------------------------- 1 | import java.io.Serializable; 2 | 3 | public class Person implements Serializable { 4 | 5 | private static final long serialVersionUID = 4801633306273802062L; 6 | 7 | private int id; 8 | private String name; 9 | 10 | public Person(int id, String name) { 11 | this.id = id; 12 | this.name = name; 13 | } 14 | 15 | @Override 16 | public String toString() { 17 | return "Person [id=" + id + ", name=" + name + "]"; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Serialization/ReadObjects.java: -------------------------------------------------------------------------------- 1 | import java.io.FileInputStream; 2 | import java.io.FileNotFoundException; 3 | import java.io.IOException; 4 | import java.io.ObjectInputStream; 5 | 6 | 7 | 8 | public class ReadObjects { 9 | 10 | 11 | public static void main(String[] args) { 12 | System.out.println("Reading objects..."); 13 | 14 | try(FileInputStream fi = new FileInputStream("people.bin")) { 15 | 16 | ObjectInputStream os = new ObjectInputStream(fi); 17 | 18 | Person person1 = (Person)os.readObject(); 19 | Person person2 = (Person)os.readObject(); 20 | 21 | os.close(); 22 | 23 | System.out.println(person1); 24 | System.out.println(person2); 25 | 26 | } catch (FileNotFoundException e) { 27 | // TODO Auto-generated catch block 28 | e.printStackTrace(); 29 | } catch (IOException e) { 30 | // TODO Auto-generated catch block 31 | e.printStackTrace(); 32 | } catch (ClassNotFoundException e) { 33 | // TODO Auto-generated catch block 34 | e.printStackTrace(); 35 | } 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/Serialization/WriteObjects.java: -------------------------------------------------------------------------------- 1 | import java.io.FileNotFoundException; 2 | import java.io.FileOutputStream; 3 | import java.io.IOException; 4 | import java.io.ObjectOutputStream; 5 | 6 | 7 | 8 | public class WriteObjects { 9 | 10 | public static void main(String[] args) { 11 | System.out.println("Writing objects..."); 12 | 13 | Person mike = new Person(543, "Mike"); 14 | Person sue = new Person(123, "Sue"); 15 | 16 | System.out.println(mike); 17 | System.out.println(sue); 18 | 19 | try(FileOutputStream fs = new FileOutputStream("people.bin")) { 20 | 21 | ObjectOutputStream os = new ObjectOutputStream(fs); 22 | 23 | os.writeObject(mike); 24 | os.writeObject(sue); 25 | 26 | os.close(); 27 | 28 | } catch (FileNotFoundException e) { 29 | // TODO Auto-generated catch block 30 | e.printStackTrace(); 31 | } catch (IOException e) { 32 | // TODO Auto-generated catch block 33 | e.printStackTrace(); 34 | } 35 | 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/SetterAndThis.java: -------------------------------------------------------------------------------- 1 | class Frog { 2 | private String name; 3 | private int age; 4 | 5 | public void setName(String name) { 6 | this.name = name; 7 | } 8 | 9 | public void setAge(int age) { 10 | this.age = age; 11 | } 12 | 13 | public String getName() { 14 | return name; 15 | } 16 | 17 | public int getAge() { 18 | return age; 19 | } 20 | 21 | public void setInfo(String name, int age) { 22 | setName(name); 23 | setAge(age); 24 | } 25 | } 26 | 27 | public class SetterAndThis { 28 | 29 | public static void main(String[] args) { 30 | 31 | Frog frog1 = new Frog(); 32 | 33 | //frog1.name = "Bertie"; 34 | //frog1.age = 1; 35 | 36 | frog1.setName("Bertie"); 37 | frog1.setAge(1); 38 | 39 | System.out.println(frog1.getName()); 40 | } 41 | 42 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/StaticAndFinal.java: -------------------------------------------------------------------------------- 1 | class Thing { 2 | public final static int LUCKY_NUMBER = 7; 3 | 4 | public String name; 5 | public static String description; 6 | 7 | public static int count = 0; 8 | 9 | public int id; 10 | 11 | public Thing() { 12 | 13 | id = count; 14 | 15 | count++; 16 | } 17 | 18 | public void showName() { 19 | System.out.println("Object id: " + id + ", " + description + ": " + name); 20 | } 21 | 22 | public static void showInfo() { 23 | System.out.println(description); 24 | // Won't work: System.out.println(name); 25 | } 26 | } 27 | 28 | 29 | public class StaticAndFinal { 30 | 31 | public static void main(String[] args) { 32 | 33 | Thing.description = "I am a thing"; 34 | 35 | Thing.showInfo(); 36 | 37 | System.out.println("Before creating objects, count is: " + Thing.count); 38 | 39 | Thing thing1 = new Thing(); 40 | Thing thing2 = new Thing(); 41 | 42 | System.out.println("After creating objects, count is: " + Thing.count); 43 | 44 | thing1.name = "Bob"; 45 | thing2.name = "Sue"; 46 | 47 | thing1.showName(); 48 | thing2.showName(); 49 | 50 | System.out.println(Math.PI); 51 | 52 | System.out.println(Thing.LUCKY_NUMBER); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/SwitchCase.java: -------------------------------------------------------------------------------- 1 | import java.util.Scanner; 2 | 3 | public class SwitchCase{ 4 | 5 | public static void main(String[] args) { 6 | 7 | Scanner input = new Scanner(System.in); 8 | 9 | System.out.println("Please enter a command: "); 10 | String text = input.nextLine(); 11 | 12 | switch (text) { 13 | case "start": 14 | System.out.println("Machine started!"); 15 | break; 16 | 17 | case "stop": 18 | System.out.println("Machine stopped."); 19 | break; 20 | 21 | default: 22 | System.out.println("Command not recognized"); 23 | } 24 | } 25 | 26 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/ToStringMethods.java: -------------------------------------------------------------------------------- 1 | class Frog { 2 | 3 | private int id; 4 | private String name; 5 | 6 | public Frog(int id, String name) { 7 | this.id = id; 8 | this.name = name; 9 | } 10 | 11 | public String toString() { 12 | 13 | return String.format("%-4d: %s", id, name); 14 | 15 | /* 16 | StringBuilder sb = new StringBuilder(); 17 | sb.append(id).append(": ").append(name); 18 | 19 | return sb.toString(); 20 | */ 21 | } 22 | } 23 | 24 | public class ToStringMethods { 25 | 26 | public static void main(String[] args) { 27 | Frog frog1 = new Frog(7, "Freddy"); 28 | Frog frog2 = new Frog(5, "Roger"); 29 | 30 | System.out.println(frog1); 31 | System.out.println(frog2); 32 | } 33 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/TryWithResources/App.java: -------------------------------------------------------------------------------- 1 | class Temp implements AutoCloseable { 2 | 3 | @Override 4 | public void close() throws Exception { 5 | System.out.println("Closing!"); 6 | throw new Exception("oh no!"); 7 | } 8 | 9 | } 10 | 11 | 12 | public class App { 13 | 14 | public static void main(String[] args) { 15 | 16 | try(Temp temp = new Temp()) { 17 | 18 | } catch (Exception e) { 19 | // TODO Auto-generated catch block 20 | e.printStackTrace(); 21 | } 22 | 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/TryWithResources/App2.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedReader; 2 | import java.io.File; 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | public class App2 { 8 | 9 | public static void main(String[] args) { 10 | File file = new File("test.txt"); 11 | 12 | try (BufferedReader br = new BufferedReader(new FileReader(file))) { 13 | String line; 14 | 15 | while ((line = br.readLine()) != null) { 16 | System.out.println(line); 17 | } 18 | } catch (FileNotFoundException e) { 19 | System.out.println("Can't find file " + file.toString()); 20 | } catch (IOException e) { 21 | System.out.println("Unable to read file " + file.toString()); 22 | } 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/UpcastingAndDowncasting.java: -------------------------------------------------------------------------------- 1 | class Machine { 2 | public void start() { 3 | System.out.println("Machine started."); 4 | } 5 | } 6 | 7 | class Camera extends Machine { 8 | public void start() { 9 | System.out.println("Camera started."); 10 | } 11 | 12 | public void snap() { 13 | System.out.println("Photo taken."); 14 | } 15 | } 16 | 17 | 18 | public class UpcastingAndDowncasting { 19 | public static void main(String[] args) { 20 | 21 | Machine machine1 = new Machine(); 22 | Camera camera1 = new Camera(); 23 | 24 | machine1.start(); 25 | camera1.start(); 26 | camera1.snap(); 27 | 28 | // Upcasting 29 | Machine machine2 = camera1; 30 | machine2.start(); 31 | // error: machine2.snap(); 32 | 33 | // Downcasting 34 | Machine machine3 = new Camera(); 35 | Camera camera2 = (Camera)machine3; 36 | camera2.start(); 37 | camera2.snap(); 38 | 39 | // Doesn't work --- runtime error. 40 | Machine machine4 = new Machine(); 41 | // Camera camera3 = (Camera)machine4; 42 | // camera3.start(); 43 | // camera3.snap(); 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/UsingGenerics.java: -------------------------------------------------------------------------------- 1 | import java.util.ArrayList; 2 | import java.util.HashMap; 3 | 4 | class Animal { 5 | 6 | } 7 | 8 | 9 | public class UsingGenerics { 10 | 11 | public static void main(String[] args) { 12 | 13 | /////////////////// Before Java 5 //////////////////////// 14 | ArrayList list = new ArrayList(); 15 | 16 | list.add("apple"); 17 | list.add("banana"); 18 | list.add("orange"); 19 | 20 | String fruit = (String)list.get(1); 21 | 22 | System.out.println(fruit); 23 | 24 | /////////////// Modern style ////////////////////////////// 25 | 26 | ArrayList strings = new ArrayList(); 27 | 28 | strings.add("cat"); 29 | strings.add("dog"); 30 | strings.add("alligator"); 31 | 32 | String animal = strings.get(1); 33 | 34 | System.out.println(animal); 35 | 36 | 37 | ///////////// There can be more than one type argument //////////////////// 38 | 39 | HashMap map = new HashMap(); 40 | 41 | 42 | //////////// Java 7 style ///////////////////////////////// 43 | 44 | ArrayList someList = new ArrayList<>(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/UsingStrings.java: -------------------------------------------------------------------------------- 1 | public class UsingStrings { 2 | public static void main(String[] args) { 3 | 4 | int myInt = 7; 5 | 6 | String text = "Hello"; 7 | 8 | String blank = " "; 9 | 10 | String name = "Bob"; 11 | 12 | String greeting = text + blank + name; 13 | 14 | System.out.println(greeting); 15 | 16 | System.out.println("Hello" + " " + "Bob"); 17 | 18 | System.out.println("My integer is: " + myInt); 19 | 20 | double myDouble = 7.8; 21 | 22 | System.out.println("My number is: " + myDouble + "."); 23 | } 24 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/UsingVariables.java: -------------------------------------------------------------------------------- 1 | public class UsingVariables { 2 | 3 | public static void main(String[] args) { 4 | int myNumber = 88; 5 | short myShort = 847; 6 | long myLong = 9797; 7 | 8 | double myDouble = 7.3243; 9 | float myFloat = 324.3f; 10 | 11 | char myChar = 'y'; 12 | boolean myBoolean = false; 13 | 14 | byte myByte = 127; 15 | 16 | 17 | System.out.println(myNumber); 18 | System.out.println(myShort); 19 | System.out.println(myLong); 20 | System.out.println(myDouble); 21 | System.out.println(myFloat); 22 | System.out.println(myChar); 23 | System.out.println(myBoolean); 24 | System.out.println(myByte); 25 | } 26 | 27 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/WhileLoop.java: -------------------------------------------------------------------------------- 1 | public class WhileLoop { 2 | public static void main(String[] args) { 3 | 4 | int value = 0; 5 | 6 | while(value < 10) 7 | { 8 | System.out.println("Hello " + value); 9 | 10 | value = value + 1; 11 | } 12 | } 13 | } -------------------------------------------------------------------------------- /Java Basics/Basics_of_java/WritingTextFiles.java: -------------------------------------------------------------------------------- 1 | import java.io.BufferedWriter; 2 | import java.io.File; 3 | import java.io.FileWriter; 4 | import java.io.IOException; 5 | 6 | 7 | public class WritingTextFiles { 8 | 9 | 10 | public static void main(String[] args) { 11 | File file = new File("test.txt"); 12 | 13 | try (BufferedWriter br = new BufferedWriter(new FileWriter(file))) { 14 | br.write("This is line one"); 15 | br.newLine(); 16 | br.write("This is line two"); 17 | br.newLine(); 18 | br.write("Last line."); 19 | } catch (IOException e) { 20 | System.out.println("Unable to read file " + file.toString()); 21 | } 22 | 23 | 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /Java Basics/README.md.txt: -------------------------------------------------------------------------------- 1 | This folder contains all the basics of java programming for the beginners. 2 | All the basics of java with code in the given folder. -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/CircularLinkedList.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | class Node{ 5 | public: 6 | int data; 7 | Node* next; 8 | }; 9 | 10 | //Traversing through the circular linked list 11 | void circular_ll_traversal(Node* head){ 12 | Node* p = head; 13 | do{ 14 | cout<data<<" "; 15 | p=p->next; 16 | }while(p!=head); 17 | } 18 | //Inserting at first 19 | Node* insertAtFirst(Node* head, int data){ 20 | Node* zero = new Node(); 21 | zero->data=data; 22 | 23 | Node* p=head; 24 | while(p->next!=head){ 25 | p=p->next; 26 | } 27 | p->next = zero; 28 | zero->next = head; 29 | head= zero; 30 | return head; 31 | 32 | } 33 | //Inserting at the last 34 | Node* insertAtLast(Node* head,int data){ 35 | Node* sixth = new Node(); 36 | sixth->data=data; 37 | 38 | Node* p = head; 39 | while(p->next!=head){ 40 | p=p->next; 41 | } 42 | p->next=sixth; 43 | sixth->next=head; 44 | return head; 45 | 46 | } 47 | //Inserting at a specific index 48 | Node* InsertAtIndex(Node* head,int data,int index){ 49 | Node* between = new Node(); 50 | between->data=data; 51 | int i=0; 52 | Node* p=head; 53 | while(i!=index-1){ 54 | p=p->next; 55 | i++; 56 | } 57 | between->next = p->next; 58 | p->next = between; 59 | return head; 60 | 61 | } 62 | 63 | 64 | int main(){ 65 | Node* head=new Node(); 66 | Node* second =new Node(); 67 | Node* third =new Node(); 68 | Node* fourth =new Node(); 69 | Node* fifth =new Node(); 70 | 71 | head->data=23; 72 | head->next=second; 73 | 74 | second->data=12; 75 | second->next=third; 76 | 77 | third->data=34; 78 | third->next=fourth; 79 | 80 | fourth->data=56; 81 | fourth->next=fifth; 82 | 83 | fifth->data=90; 84 | fifth->next=head; 85 | 86 | cout<<"Circular linked list before Insertion\n"; 87 | circular_ll_traversal(head); 88 | cout<<"\n"; 89 | 90 | //head=insertAtFirst(head, 45); 91 | //cout<<"\n"; 92 | //circular_ll_traversal(head); 93 | 94 | //head = insertAtLast(head,53); 95 | head = InsertAtIndex(head,44,3); 96 | 97 | cout<<"Circular linked list after Insertion\n"; 98 | circular_ll_traversal(head); 99 | cout<<"\n"; 100 | 101 | return 0; 102 | 103 | } 104 | -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Taniya Kulkarni](https://github.com/taniyask) 8 | - [Akshita Sharma](https://github.com/Akshitasharma01) 9 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 10 | - [Ashutosh Pandey](https://github.com/DataCrusade1999) 11 | - [Ananthakrishnan Nair RS](https://github.com/akrish4) 12 | -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Doubly_linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | struct Node { 4 | int data; 5 | struct Node *prev; 6 | struct Node *next; 7 | }; 8 | struct Node* head = NULL; 9 | void insert(int newdata) { 10 | struct Node* newnode = (struct Node*) malloc(sizeof(struct Node)); 11 | newnode->data = newdata; 12 | newnode->prev = NULL; 13 | newnode->next = head; 14 | if(head != NULL) 15 | head->prev = newnode ; 16 | head = newnode; 17 | } 18 | void display() { 19 | struct Node* ptr; 20 | ptr = head; 21 | while(ptr != NULL) { 22 | cout<< ptr->data <<" "; 23 | ptr = ptr->next; 24 | } 25 | } 26 | int main() { 27 | insert(3); 28 | insert(1); 29 | insert(7); 30 | insert(2); 31 | insert(9); 32 | cout<<"The doubly linked list is: "; 33 | display(); 34 | return 0; 35 | } -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Intersection.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "dll.h" 4 | //Author: Taniya Kulkarni 5 | 6 | struct node *list3 = NULL; 7 | 8 | void intersection (struct node *head1, struct node *head2) 9 | { 10 | isempty(head1); 11 | isempty(head2); 12 | if( head1 != NULL && head2 != NULL) 13 | { 14 | struct node *temp1 = head1; 15 | while (temp1 != NULL) 16 | { 17 | struct node *temp2 = head2; 18 | while (temp2 != NULL) 19 | { 20 | if(temp2->num == temp1->num) 21 | { 22 | insert_end (temp1->num, &list3); 23 | } 24 | temp2 = temp2->next; 25 | } 26 | temp1 = temp1->next; 27 | } 28 | duplicates (&list3); 29 | } 30 | } 31 | 32 | void main() 33 | { 34 | int choice1, choice2; 35 | struct node *head1 = NULL; 36 | struct node *head2 = NULL; 37 | printf ("\nLIST 1:"); 38 | printf("\n --------------------------\n"); 39 | do 40 | { 41 | int item; 42 | printf("\n ENTER NUMBER INTO LIST 1: "); 43 | scanf("%d", &item); 44 | insert_end (item, &head1); 45 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): "); 46 | scanf("%d", &choice1); 47 | }while(choice1); 48 | printf ("\nLIST 2:"); 49 | printf("\n --------------------------\n"); 50 | do 51 | { 52 | int item; 53 | printf("\n ENTER NUMBER INTO LIST 2: "); 54 | scanf("%d", &item); 55 | insert_end (item, &head2); 56 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): "); 57 | scanf("%d", &choice2); 58 | }while(choice2); 59 | printf("\n----------------------------"); 60 | printf("\nLIST 1: \n"); 61 | display(head1); 62 | printf("\n----------------------------"); 63 | printf("\n----------------------------"); 64 | printf("\nLIST 2: \n"); 65 | display(head2); 66 | printf("\n----------------------------"); 67 | printf("\n----------------------------"); 68 | printf("\n LIST 3: \n"); 69 | intersection(head1, head2); 70 | display(list3); 71 | printf("\n----------------------------\n"); 72 | } -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/LinkListUsingSTL.CPP: -------------------------------------------------------------------------------- 1 | //Implementation of SLL 2 | #include 3 | #include 4 | struct list 5 | { 6 | int data; 7 | struct list *next; 8 | }; 9 | 10 | typedef struct list ll; 11 | 12 | class sll 13 | { 14 | public: 15 | ll *create(ll *); 16 | void display(ll *); 17 | ll *insert(ll *); 18 | ll *Delete(ll *); 19 | }; 20 | 21 | void main() 22 | { 23 | sll l; 24 | ll *node; 25 | clrscr(); 26 | node = l.create(node); 27 | cout<<"\n List is : "; 28 | l.display(node); 29 | cout<<"\n *****************"; 30 | cout<<"\n\n Node Insertion "; 31 | cout<<"\n *****************\n"; 32 | node = l.insert(node); 33 | cout<<"\n List after insertion : "; 34 | l.display(node); 35 | //insertL(node); 36 | //insertM(node); 37 | cout<<"\n ****************"; 38 | cout<<"\n\n Node Deletion "; 39 | cout<<"\n *****************\n"; 40 | node = l.Delete(node); 41 | cout<<"\n List after deletion : "; 42 | l.display(node); 43 | getch(); 44 | } 45 | 46 | ll *sll::create(ll *node) 47 | { 48 | char ch; 49 | ll *start; 50 | start = node; 51 | do{ 52 | cout<<"\n Enter the node : "; 53 | cin>>node->data; 54 | node->next = new ll; 55 | node = node->next; 56 | node->next = NULL; 57 | //fflush(stdin); 58 | cout<<"\n Do you want to another node (y/n) "; 59 | cin>>ch; 60 | }while(ch != 'n'); 61 | return start; 62 | } 63 | void sll::display(ll *node) 64 | { 65 | while(node->next) 66 | { 67 | cout<<" "<data; 68 | node = node->next; 69 | } 70 | } 71 | ll *sll::insert(ll *node) 72 | { 73 | ll *F, *h; 74 | int pos, i = 1; 75 | F = new ll; 76 | h = node; 77 | if(node) 78 | { 79 | cout<<"\n Enter position, where node to be inserted: "; 80 | cin>>pos; 81 | 82 | cout<<"\n Enter the node :"; 83 | cin>>F->data; 84 | 85 | if(pos == 1) 86 | { 87 | F->next = h; 88 | h = F; 89 | } 90 | else 91 | { 92 | while(inext; 95 | i++; 96 | } 97 | F->next = node->next; 98 | node->next = F; 99 | } 100 | } 101 | return h; 102 | } 103 | 104 | ll *sll::Delete(ll *node) 105 | { 106 | ll *start, *d; 107 | int pos, i = 1; 108 | start = node; 109 | cout<<"\n Enter the position, from where node to be deleted : "; 110 | cin>>pos; 111 | while(inext; 114 | i++; 115 | } 116 | d = node->next; 117 | node->next = d->next; 118 | delete(d); 119 | return start; 120 | } 121 | 122 | 123 | 124 | -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Palindrome_Linked_list.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | class Node { 6 | public: 7 | int data; 8 | 9 | Node(int d){ 10 | data = d; 11 | } 12 | Node *ptr; 13 | }; 14 | 15 | bool isPalindrome(Node* head){ 16 | // This pointer will allow the first traversal 17 | // of the linked list 18 | Node* next= head; 19 | // Declare a stack 20 | stack s; 21 | 22 | // Traverse the linked list and add its elements 23 | // to the stack 24 | while(next != NULL){ 25 | s.push(next->data); 26 | next = next->ptr; 27 | } 28 | 29 | // Iterate the linked list again and 30 | // check by each element with the stack 31 | while(head != NULL ){ 32 | int i=s.top(); 33 | 34 | if(head -> data != i){ 35 | return false; 36 | } 37 | // Move to the next element in stack and the list 38 | s.pop(); 39 | head=head->ptr; 40 | } 41 | 42 | return true; 43 | } 44 | 45 | 46 | //Main function 47 | int main(){ 48 | 49 | Node one = Node(1); 50 | Node two = Node(3); 51 | Node three = Node(5); 52 | Node four = Node(3); 53 | Node five = Node(1); 54 | 55 | // Initialize the pointers of the Linked List 56 | five.ptr = NULL; 57 | one.ptr = &two; 58 | two.ptr = &three; 59 | three.ptr = &four; 60 | four.ptr = &five; 61 | Node* temp = &one; 62 | 63 | 64 | // Call function with head of the linked list 65 | int result = isPalindrome(&one); 66 | if(result == 1) 67 | cout<<"Linked list is a palindrome\n"; 68 | else 69 | cout<<"Linked list is NOT a palindrome\n"; 70 | 71 | } 72 | -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Remove_Duplicates.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "dll.h" 4 | //Author: Taniya Kulkarni 5 | 6 | 7 | 8 | void main() 9 | { 10 | int choice; 11 | struct node *head = NULL; 12 | do{ 13 | int item; 14 | printf("\n ENTER NUMBER INTO LIST: "); 15 | scanf("%d", &item); 16 | insert_end (item, &head); 17 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): "); 18 | scanf("%d", &choice); 19 | }while(choice); 20 | printf("\n----------------------------"); 21 | printf("\nOLD LIST (WITH DUPLICATES): \n"); 22 | display(head); 23 | printf("\n----------------------------"); 24 | printf("\nNEW LIST (WITHOUT DUPLICATES): \n"); 25 | duplicates(&head); 26 | display(head); 27 | printf("\n"); 28 | } -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/Unions.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "dll.h" 4 | //Author: Taniya Kulkarni 5 | 6 | struct node *list3=NULL; 7 | 8 | void union_list(struct node *head1, struct node *head2) 9 | { 10 | isempty(head1); 11 | isempty(head2); 12 | if(head1 != NULL && head2 != NULL) 13 | { 14 | struct node *temp1 = head1; 15 | struct node *temp2 = head2; 16 | while(temp1 != NULL) 17 | { 18 | insert_end(temp1->num, &list3); 19 | temp1 = temp1->next; 20 | } 21 | while(temp2 != NULL) 22 | { 23 | insert_end(temp2->num, &list3); 24 | temp2 = temp2->next; 25 | } 26 | } 27 | duplicates(&list3); 28 | 29 | } 30 | 31 | void main() 32 | { 33 | int choice1, choice2; 34 | struct node *head1 = NULL; 35 | struct node *head2 = NULL; 36 | printf ("\nLIST 1:"); 37 | printf("\n --------------------------\n"); 38 | do{ 39 | int item; 40 | printf("\n ENTER NUMBER INTO LIST 1: "); 41 | scanf("%d", &item); 42 | insert_end (item, &head1); 43 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): "); 44 | scanf("%d", &choice1); 45 | }while(choice1); 46 | printf ("\nLIST 2:"); 47 | printf("\n --------------------------\n"); 48 | do{ 49 | int item; 50 | printf("\n ENTER NUMBER INTO LIST 2: "); 51 | scanf("%d", &item); 52 | insert_end (item, &head2); 53 | printf("\n DO YOU WISH TO ENTER ANOTHER NUMBER INTO THE LIST? (Any number/0): "); 54 | scanf("%d", &choice2); 55 | }while(choice2); 56 | printf("\n----------------------------"); 57 | printf("\nLIST 1: \n"); 58 | display(head1); 59 | printf("\n----------------------------"); 60 | printf("\n----------------------------"); 61 | printf("\nLIST 2: \n"); 62 | display(head2); 63 | printf("\n----------------------------"); 64 | printf("\n----------------------------"); 65 | printf("\n LIST 3: \n"); 66 | union_list(head1, head2); 67 | display(list3); 68 | printf("\n----------------------------\n"); 69 | } -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/dll.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | //Author: Taniya Kulkarni 4 | 5 | //Node for Doubly linked list. 6 | struct node 7 | { 8 | int num; 9 | struct node *prev, *next; 10 | }; 11 | struct node *new, *ptr; 12 | int size=0; 13 | 14 | //Function to check if list is empty 15 | void isempty(struct node *head) 16 | { 17 | if (head==NULL) 18 | { 19 | printf("\n LIST IS EMPTY!\n"); 20 | return; 21 | } 22 | return; 23 | } 24 | 25 | 26 | 27 | //Function to insert node at the end 28 | void insert_end (int item, struct node **head_ref) 29 | { 30 | struct node *temp; 31 | new=(struct node *) malloc (sizeof(struct node)); 32 | new->num = item; 33 | new->next = NULL; 34 | if (*head_ref == NULL) 35 | { 36 | *head_ref = new; 37 | size++; 38 | return; 39 | } 40 | 41 | else 42 | { 43 | temp = *head_ref; 44 | while (temp -> next != NULL) 45 | { 46 | temp = temp->next; 47 | } 48 | temp->next = new; 49 | new->prev = temp; 50 | } 51 | size++; 52 | } 53 | 54 | 55 | 56 | 57 | 58 | void display (struct node *head) 59 | { 60 | 61 | if (head != NULL) 62 | { 63 | struct node *temp; 64 | temp=head; 65 | while(temp->next != NULL) 66 | { 67 | printf (" %d -> ", temp->num); 68 | temp= temp->next; 69 | } 70 | printf("%d ", temp->num); 71 | } 72 | } 73 | 74 | 75 | //Function to check for duplicates 76 | void duplicates(struct node **head_ref) 77 | { 78 | struct node *temp, *copy; 79 | isempty(*head_ref); 80 | if(*head_ref != NULL) 81 | { 82 | temp = *head_ref; 83 | while (temp != NULL && temp->next != NULL) 84 | { 85 | ptr = temp; 86 | while(ptr -> next != NULL) 87 | { 88 | if(temp->num == ptr->next->num) //If duplicate found, then delete the copy. 89 | { 90 | copy = ptr->next; 91 | ptr->next = ptr->next->next; 92 | free(copy); 93 | } 94 | else 95 | { 96 | ptr= ptr->next; 97 | } 98 | } 99 | temp = temp->next; 100 | } 101 | 102 | } 103 | } -------------------------------------------------------------------------------- /LINKED LIST/c or cpp/sorting linked list.c: -------------------------------------------------------------------------------- 1 | // Problem :- Program to check whether Linked List is sorted or not. 2 | 3 | #include 4 | #include 5 | 6 | struct Node 7 | { 8 | int data; 9 | struct Node *next; 10 | }*first=NULL; 11 | 12 | void create (int A[], int n) 13 | { 14 | int i; 15 | struct Node *t, *last; 16 | first=(struct Node *)malloc(sizeof(struct Node)); 17 | first->data=A[0]; 18 | first->next=NULL; 19 | last=first; 20 | for(i=1; idata=A[i]; 24 | t->next=NULL; 25 | last->next=t; 26 | last=t; 27 | } 28 | } 29 | 30 | int isSorted(struct Node *p) 31 | { 32 | int x = -32768; 33 | while(p!=NULL) 34 | { 35 | if(p->data < x) 36 | return 0; 37 | x = p->data; 38 | p = p->next; 39 | } 40 | return 1; 41 | } 42 | 43 | int main() 44 | { 45 | int A[]={10, 2, 30, 40, 50}; 46 | create(A, 5); 47 | if(isSorted(first)) 48 | { 49 | printf("Linked List is Sorted\n"); 50 | } 51 | else 52 | { 53 | printf("Linked List is Not Sorted\n"); 54 | } 55 | return 0; 56 | } 57 | 58 | 59 | /* 60 | 61 | Output :- 62 | 63 | Linked List is Not Sorted 64 | 65 | */ 66 | -------------------------------------------------------------------------------- /LINKED LIST/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Abhishek Kumar Vikrant](https://github.com/AbhiVikrant) 8 | - [Pari Zunake](https://github.com/psz8) 9 | -------------------------------------------------------------------------------- /LINKED LIST/java/Sorting/MergeSort.md: -------------------------------------------------------------------------------- 1 | ## Best Sorting Algorithms for Linked List 2 | ---------- 3 | *Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible.* 4 | 5 | 6 | 7 | AbhishekVikrant 8 | 9 | ### Steps Required for Sorting the LinkedList using Merge Sort 10 | 11 | ```language 12 | MergeSort(headRef) 13 | 1) If the head is NULL or there is only one element in the Linked List 14 | then return. 15 | 2) Else divide the linked list into two halves. 16 | FrontBackSplit(head, &a, &b); /* a and b are two halves */ 17 | 3) Sort the two halves a and b. 18 | MergeSort(a); 19 | MergeSort(b); 20 | 4) Merge the sorted a and b (using SortedMerge() discussed here) 21 | and update the head pointer using headRef. 22 | *headRef = SortedMerge(a, b); 23 | ``` 24 | 25 | ### Descriptions 26 | *Let head be the first node of the linked list to be sorted and headRef be the pointer to head. Note that we need a reference to head in MergeSort() as the below implementation changes next links to sort the linked lists (not data at the nodes), so head node has to be changed if the data at the original head is not the smallest value in the linked list.* 27 | 28 | ### Reference 29 | [GeeksForGeeks](https://www.geeksforgeeks.org/merge-sort-for-linked-list/#:~:text=Merge%20sort%20is%20often%20preferred,be%20the%20pointer%20to%20head.) 30 | 31 | 32 |

33 | Thanks Coding ! 34 | Thanks for Open Source Contribution! 35 |

-------------------------------------------------------------------------------- /LINKED LIST/java/Sorting/Sort-Linked-List-768x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/LINKED LIST/java/Sorting/Sort-Linked-List-768x384.png -------------------------------------------------------------------------------- /LINKED LIST/java/linkedlist.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | public class Test { 4 | 5 | public static void main(String args[]) 6 | { 7 | // Creating object of the 8 | // class linked list 9 | LinkedList ll 10 | = new LinkedList(); 11 | 12 | // Adding elements to the linked list 13 | ll.add("A"); 14 | ll.add("B"); 15 | ll.addLast("C"); 16 | ll.addFirst("D"); 17 | ll.add(2, "E"); 18 | 19 | System.out.println(ll); 20 | 21 | ll.remove("B"); 22 | ll.remove(3); 23 | ll.removeFirst(); 24 | ll.removeLast(); 25 | 26 | System.out.println(ll); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /LINKED LIST/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Karan Wagh](https://github.com/FlashTech-dev) 8 | - [Vivek Ray](https://github.com/vivekray903) 9 | - [Gaurav Kulkarni](https://github.com/gkulk007) 10 | 11 | 12 | -------------------------------------------------------------------------------- /LINKED LIST/py/is_palindrome.py: -------------------------------------------------------------------------------- 1 | def is_palindrome(head): 2 | if not head: 3 | return True 4 | # split the list to two parts 5 | fast, slow = head.next, head 6 | while fast and fast.next: 7 | fast = fast.next.next 8 | slow = slow.next 9 | second = slow.next 10 | slow.next = None # Don't forget here! But forget still works! 11 | # reverse the second part 12 | node = None 13 | while second: 14 | nxt = second.next 15 | second.next = node 16 | node = second 17 | second = nxt 18 | # compare two parts 19 | # second part has the same or one less node 20 | while node: 21 | if node.val != head.val: 22 | return False 23 | node = node.next 24 | head = head.next 25 | return True 26 | 27 | 28 | def is_palindrome_stack(head): 29 | if not head or not head.next: 30 | return True 31 | 32 | # 1. Get the midpoint (slow) 33 | slow = fast = cur = head 34 | while fast and fast.next: 35 | fast, slow = fast.next.next, slow.next 36 | 37 | # 2. Push the second half into the stack 38 | stack = [slow.val] 39 | while slow.next: 40 | slow = slow.next 41 | stack.append(slow.val) 42 | 43 | # 3. Comparison 44 | while stack: 45 | if stack.pop() != cur.val: 46 | return False 47 | cur = cur.next 48 | 49 | return True 50 | 51 | 52 | def is_palindrome_dict(head): 53 | if not head or not head.next: 54 | return True 55 | d = {} 56 | pos = 0 57 | while head: 58 | if head.val in d.keys(): 59 | d[head.val].append(pos) 60 | else: 61 | d[head.val] = [pos] 62 | head = head.next 63 | pos += 1 64 | checksum = pos - 1 65 | middle = 0 66 | for v in d.values(): 67 | if len(v) % 2 != 0: 68 | middle += 1 69 | else: 70 | step = 0 71 | for i in range(0, len(v)): 72 | if v[i] + v[len(v) - 1 - step] != checksum: 73 | return False 74 | step += 1 75 | if middle > 1: 76 | return False 77 | return True 78 | 79 | # Implemented by Gaurav Kulkarni 80 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma ) 7 | - [Bhavesh Joshi](https://github.com/Wittty-Panda ) 8 | - [Atharv Karanjkar](https://github.com/atharvkaranjkar) -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/Herarchical_inheritance.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 40 | 41 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/Herarchical_inheritance.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/bin/Debug/Herarchical_inheritance.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/bin/Debug/Herarchical_inheritance.exe -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/main.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement Hierarchical Inheritance 2 | #include 3 | using namespace std; 4 | // base class 5 | class Vehicle 6 | { 7 | public: 8 | Vehicle() 9 | { 10 | cout << "This is a Vehicle" << endl; 11 | } 12 | }; 13 | // first sub class 14 | class Car: public Vehicle 15 | { 16 | 17 | }; 18 | // second sub class 19 | class Bus: public Vehicle 20 | { 21 | }; 22 | // main function 23 | int main() 24 | { // creating object of sub class will 25 | // invoke the constructor of base class 26 | Car obj1; 27 | Bus obj2; 28 | return 0; 29 | } 30 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/obj/Debug/main.o: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Herarchical_inheritance/obj/Debug/main.o -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.cbp: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 40 | 41 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.depend: -------------------------------------------------------------------------------- 1 | # depslib dependency file v1.0 2 | 1602068805 source:e:\programming\teaching\hybrid_inheritance\main.cpp 3 | 4 | 5 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/Hybrid_Inheritance.layout: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/bin/Debug/Hybrid_Inheritance.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms/35e6685cfca8d43fbef75dbe78e4527b49be6e17/OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/bin/Debug/Hybrid_Inheritance.exe -------------------------------------------------------------------------------- /OBJECT ORIENTED PROGRAMMING/c or cpp/Hybrid_Inheritance/main.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Hybrid Inheritance 2 | #include 3 | using namespace std; 4 | 5 | // base class 6 | class Vehicle 7 | { 8 | public: 9 | Vehicle() 10 | { 11 | cout << "This is a Vehicle" << endl; 12 | } 13 | }; 14 | //base class 15 | class Fare 16 | { 17 | public: 18 | Fare() 19 | { 20 | cout< 4 | 5 | using namespace std; 6 | 7 | class N; 8 | 9 | class M{ 10 | int num; 11 | public: 12 | M(){ 13 | cout<<"Enter value (M)"; 14 | cin>>num; 15 | }; 16 | void displaydata(); 17 | ~M(){ 18 | 19 | } 20 | friend void comp(M x, N y); 21 | }; 22 | 23 | class N{ 24 | int num; 25 | friend void comp(M x, N y); 26 | public: 27 | N(){ 28 | cout<<"Enter value (N)"; 29 | cin>>num; 30 | }; 31 | void displaydata(); 32 | ~N(){ 33 | 34 | } 35 | //friend void comp(M x, N y); 36 | }; 37 | void comp(M x, N y){ 38 | if (x.num>y.num){ 39 | cout<<"\n Greater number is : "< 3 | using namespace std; 4 | 5 | class A //single base class 6 | { 7 | public: 8 | int x, y; 9 | void getdata() 10 | { 11 | cout << "\nEnter value of x and y:\n"; cin >> x >> y; 12 | } 13 | }; 14 | class B : public A //B is derived from class base 15 | { 16 | public: 17 | void product() 18 | { 19 | cout << "\nProduct= " << x * y; 20 | } 21 | }; 22 | class C : public A //C is also derived from class base 23 | { 24 | public: 25 | void sum() 26 | { 27 | cout << "\nSum= " << x + y; 28 | } 29 | }; 30 | int main() 31 | { 32 | B obj1; //object of derived class B 33 | C obj2; //object of derived class C 34 | obj1.getdata(); 35 | obj1.product(); 36 | obj2.getdata(); 37 | obj2.sum(); 38 | return 0; 39 | } //end of program -------------------------------------------------------------------------------- /PATTERNS/halfpyramid.c: -------------------------------------------------------------------------------- 1 | #include 2 | int main() 3 | { 4 | int i; 5 | int j; 6 | int n=7; 7 | int x=n, y=n; 8 | for(i=1; i<=n; i++) 9 | { 10 | for(j=1; j=x && j<=y) 13 | { 14 | printf(" * "); 15 | } 16 | else 17 | { 18 | printf(""); 19 | } 20 | 21 | } 22 | 23 | x--; 24 | y++; 25 | printf("\n"); 26 | } 27 | return 0; 28 | } 29 | 30 | #OUTPUT: 31 | 32 | * 33 | * * 34 | * * * 35 | * * * * 36 | * * * * * 37 | * * * * * * 38 | -------------------------------------------------------------------------------- /PATTERNS/pascalTriangle.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | int factorial(int num) 6 | { 7 | int factorial = 1; 8 | for (int i = 2; i <= num; i++) 9 | { 10 | factorial *= i; 11 | } 12 | return factorial; 13 | } 14 | int main() 15 | { 16 | int n; 17 | cin >> n; 18 | for (int i = 0; i < n; i++) 19 | { 20 | for (int j = 0; j <= i; j++) 21 | { 22 | cout << factorial(i) / (factorial(j) * factorial(i - j)) << " "; 23 | } 24 | cout << endl; 25 | } 26 | return 0; 27 | } 28 | -------------------------------------------------------------------------------- /PATTERNS/pattern.c: -------------------------------------------------------------------------------- 1 | /* 2 | 1 3 | 2*2 4 | 3*3*3 5 | 4*4*4*4 6 | 4*4*4*4 7 | 3*3*3 8 | 2*2 9 | 1 10 | */ 11 | #include 12 | 13 | int main() 14 | { 15 | int i, j; 16 | for (i = 1; i <= 4; i++) 17 | { 18 | for (j = 1; j <= i; j++) 19 | { 20 | if (j < i) 21 | printf("%d*", i); 22 | else 23 | printf("%d", i); 24 | } 25 | printf(" \n"); 26 | } 27 | for (i = 4; i >= 1; i--) 28 | { 29 | for (j = 1; j <= i; j++) 30 | { 31 | if (j < i) 32 | printf("%d*", i); 33 | else 34 | printf("%d", i); 35 | } 36 | printf(" \n"); 37 | } 38 | return 0; 39 | } -------------------------------------------------------------------------------- /PRIMALITY TESTING ALGORITHMS/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /PRIMALITY TESTING ALGORITHMS/c or cpp/sieve.cpp: -------------------------------------------------------------------------------- 1 | //Program to find the prime numbers in O(nloglogn) 2 | #include 3 | using namespace std; 4 | 5 | void SieveOfEratosthenes(int n) 6 | { 7 | bool prime[n+1]; 8 | memset(prime, true, sizeof(prime)); 9 | 10 | for (int p=2; p*p<=n; p++) 11 | { 12 | if (prime[p] == true) 13 | { 14 | for (int i=p*p; i<=n; i += p) 15 | prime[i] = false; 16 | } 17 | } 18 | 19 | for (int p=2; p<=n; p++) 20 | if (prime[p]) 21 | cout << p << " "; 22 | } 23 | 24 | // Driver Program 25 | int main() 26 | { 27 | int n = 1000; 28 | cout << "Here are the prime numbers smaller " 29 | << " than or equal to " << n << endl; 30 | SieveOfEratosthenes(n); 31 | return 0; 32 | } 33 | -------------------------------------------------------------------------------- /PRIMALITY TESTING ALGORITHMS/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /PRIMALITY TESTING ALGORITHMS/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data-Structures-and-Algorithms 2 | 3 |

Contribute your C,CPP,JAVA and PYTHON Codes

4 | 5 |
6 | 7 |

How to contribute?

8 | 9 | 10 | 1. [Fork](https://github.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms) this repository. 11 | 2. Clone the forked repository to your computer. 12 | 13 | `https://github.com/Developer-Students-Clubs-MESCOE/Data-Structures-and-Algorithms.git` 14 | 15 | 3. Add your choice of code in any of the folder that has been created. 16 | 4. You are also welcomed to add innovative codes of your choice. 17 | 5. Your program should be interactive and please do add comments if possible. 18 | 6. Add your name in the contributors.md file just for the record. 19 | 7. Create a Pull Request 20 |
Please ⭐️ this repo if you liked it.
21 | 22 |
23 | 24 | -------------------------------------------------------------------------------- /RECURSION/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Atharva Dhamale](https://github.com/adhamale2810) 8 | - [Sphoorti Kadapa](https://github.com/Sphoortikadapa) 9 | - [Surendiran S](https://github.com/SurendiranS) 10 | -------------------------------------------------------------------------------- /RECURSION/c or cpp/Factorial.cpp: -------------------------------------------------------------------------------- 1 | /*The process in which a function calls itself is call Recursion and 2 | the corresponding function is known as Recursive Function*/ 3 | 4 | //Popular example of recursion is Factorial of a Number 5 | //-----------------------Test Input----------------------- 6 | //num = 5 7 | //Output : Factorial of 5 is 120 8 | #include 9 | using namespace std; 10 | class Factorial 11 | { 12 | public: 13 | int f(int n) 14 | { 15 | if (n == 1 or n == 0)//base condition 16 | return 1; 17 | else 18 | return n*f(n-1);//recursive function call 19 | } 20 | }; 21 | 22 | int main() 23 | { 24 | Factorial obj;//Object Creation 25 | int num; 26 | cout<<"Enter any Number:"; 27 | cin>>num; 28 | //Function call using class object 29 | cout<<"Factorial of "< 5 | 6 | using namespace std; 7 | 8 | 9 | int hcf(int x, int y){ 10 | if(x==0){ 11 | return x; 12 | } 13 | 14 | if(y==0){ 15 | return y; 16 | } 17 | 18 | if(x==y){ 19 | return x; 20 | } 21 | 22 | if(x>y){ 23 | return hcf(x-y, y); 24 | } 25 | 26 | if(y>x){ 27 | return hcf(x, y-x); 28 | } 29 | 30 | } 31 | 32 | int main(){ 33 | int x,y; 34 | cout<<"Enter the integers whose HCF you want to calculate\n"; 35 | cin>>x>>y; 36 | cout< 3 | 4 | // recursive function to calculate 5 | // multiplication of two numbers 6 | int product(int x, int y) 7 | { 8 | // if x is less than 9 | // y swap the numbers 10 | if (x < y) 11 | return product(y, x); 12 | 13 | // iteratively calculate 14 | // y times sum of x 15 | else if (y != 0) 16 | return (x + product(x, y - 1)); 17 | 18 | // if any of the two numbers is 19 | // zero return zero 20 | else 21 | return 0; 22 | } 23 | 24 | // Driver Code 25 | int main() 26 | { 27 | int num1,num2; 28 | scanf("%d %d",&num1, &num2); 29 | printf("%d", product(num1, num2)); 30 | return 0; 31 | } 32 | 33 | 34 | -------------------------------------------------------------------------------- /RECURSION/c or cpp/sum_of_square_of_binomial_coeffiecient/readme.md: -------------------------------------------------------------------------------- 1 | Program :To find the sum of square of binomial coefficient 2 | Input : Integer 3 | Output : Integer 4 | 5 | Contributed By Abhishek Jaiswal 6 | -------------------------------------------------------------------------------- /RECURSION/c or cpp/sum_of_square_of_binomial_coeffiecient/sum_of_square_of_binomial_coefficient.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Program :To find the sum of square of 3 | binomial coefficient. 4 | 5 | This Program is contributed by Abhishek Jaiswal 6 | */ 7 | #include 8 | using namespace std; 9 | 10 | int factorial(int begin, int end) 11 | { 12 | int num = 1; 13 | for (int i = begin; i <= end; i++) 14 | num *= i; 15 | 16 | return num; 17 | } 18 | 19 | int square(int n) 20 | { 21 | return factorial(n + 1, 2 * n) / factorial(1, n); 22 | } 23 | 24 | int main() 25 | { 26 | int n; 27 | cout << "Enter the number :"; 28 | cin >> n; 29 | cout << "The Sum of Square is " << square(n) << endl; 30 | return 0; 31 | } 32 | 33 | -------------------------------------------------------------------------------- /RECURSION/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Mayank Pandey](https://github.com/Mayshank18) 8 | -------------------------------------------------------------------------------- /RECURSION/java/NumberOfPaths.java: -------------------------------------------------------------------------------- 1 | 2 | import java.util.*; 3 | import java.lang.*; 4 | import java.io.*; 5 | 6 | class NumberOfPaths 7 | { 8 | public static int numberofpaths(int m,int n) 9 | { 10 | if(m==1||n==1) 11 | { 12 | return 1; 13 | } 14 | int a=numberofpaths(m-1,n); 15 | int b=numberofpaths(m,n-1); 16 | return a+b; 17 | } 18 | public static void main (String[] args) 19 | { 20 | Scanner sc=new Scanner(System.in); 21 | int i=0; 22 | int m=sc.nextInt(); 23 | int n=sc.nextInt(); 24 | System.out.println(numberofpaths(m,n)); 25 | i=i+1; 26 | } 27 | 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /RECURSION/java/all_subset_of_string.java: -------------------------------------------------------------------------------- 1 | // All subset of a string 2 | 3 | import java.util.*; 4 | 5 | public class AllSubsetOfString { 6 | 7 | public static void main(String[] args) { 8 | Scanner sc = new Scanner(System.in); 9 | String st = sc.next(); //input string to find subset 10 | ArrayList ans = new LexSort().powerSet(st); 11 | Collections.sort(ans); 12 | for(String s: ans) 13 | System.out.print(s + " "); 14 | System.out.println(); 15 | } 16 | 17 | } 18 | class LexSort 19 | { 20 | static ArrayList powerSet(String s) 21 | { 22 | ArrayList list = new ArrayList(); 23 | String a = ""; 24 | subSet( list, s, a, 0, s.length()); 25 | return list; 26 | } 27 | 28 | private static void subSet(ArrayList list, String s, String a, int i, int n) { 29 | if (i==n) { 30 | list.add(a); 31 | } else { 32 | subSet(list, s, a+s.charAt(i), i+1, n); 33 | subSet(list, s, a, i+1, n); 34 | } 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /RECURSION/java/factorial.java: -------------------------------------------------------------------------------- 1 | import java.util.*; 2 | 3 | class Factorial{ 4 | static int factor(int n){ 5 | if (n == 0 || n == 1) 6 | return 1; 7 | else 8 | return(n * factor(n-1)); 9 | } 10 | public static void main(String args[]){ 11 | int i,fact=1; 12 | int number; 13 | Scanner sc=new Scanner(System.in); 14 | number=sc.nextInt(); 15 | fact = factor(number); 16 | System.out.println("Factorial of "+number+" is: "+fact); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /RECURSION/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Lisha Ray](https://github.com/Lisharay4x3) 8 | - [Rahul Netkar](https://github.com/rahulNetkar) 9 | - [chandrau820](https://github.com/chandrau820) 10 | -------------------------------------------------------------------------------- /RECURSION/py/Factorial.py: -------------------------------------------------------------------------------- 1 | # Python Program to find factorial of a number using Recursion 2 | # Written by Lisha Ray 3 | 4 | # Function to calculate Factorial of a number 5 | def factorial(number): 6 | if number == 1: 7 | return 1 8 | else : 9 | return factorial(number-1) * number 10 | 11 | number=int(input("Enter a number = ")) 12 | print("Factorial of number = ",factorial(number)) 13 | 14 | #Output: 15 | #Enter a number = 3 16 | #Factorial of number = 6 -------------------------------------------------------------------------------- /RECURSION/py/Fibonacci_Sequence.py: -------------------------------------------------------------------------------- 1 | #fibonacci sequence starts with 0 2 | # finding nth fibonacci number using Reccursion 3 | def fibonacci(n): 4 | if(n==1 or n==2): 5 | return n-1 6 | return fibonacci(n-1)+fibonacci(n-2) 7 | n=int(input("enter which fibonacci number do you want : ")) 8 | print('fibonacci number is : ',fibonacci(n)) -------------------------------------------------------------------------------- /RECURSION/py/palindrome.py: -------------------------------------------------------------------------------- 1 | #This is a program which identifies that the given string is a palindrome or not. 2 | #A palindrome is a word that is spelled the same forward and backward. For example, rotor is a palindrome, but motor is not. 3 | #By rahulNetkar 4 | #uwu 5 | 6 | str = input("Enter the sting: ") 7 | 8 | #Returns the first character of the string str 9 | def firstCharacter(str): 10 | return str[0:1] 11 | 12 | #Returns the last character of a string str 13 | def lastCharacter(str): 14 | return str[-1:] 15 | 16 | #Returns the string that results from removing the first and the last character from str\ 17 | def middleCharacter(str): 18 | return str[1:-1] 19 | 20 | #Driver function 21 | def isPalindrome(str): 22 | #base case 1 23 | if(len(str) == 0 | len(str) == 1): 24 | return True 25 | if(len(str) == 2): 26 | if(firstCharacter(str) == lastCharacter(str)): 27 | return True 28 | else: 29 | return False 30 | #base case 2 31 | elif(firstCharacter(str) != lastCharacter(str)): 32 | return False 33 | #recursive case 34 | return isPalindrome(middleCharacter(str)) 35 | 36 | def checkPalindrome(str): 37 | print("Is this word a palindrome?") 38 | print(isPalindrome(str)) 39 | 40 | checkPalindrome(str) -------------------------------------------------------------------------------- /SEARCHING/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Sheetal Singh](https://github.com/Sheetalsingh23) 8 | -------------------------------------------------------------------------------- /SEARCHING/c or cpp/Divide_&_conquer_to_find_min_&_max.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | int min,max; 4 | int arr[10]; 5 | void minmax(int i,int j); 6 | int main() 7 | { 8 | int n; 9 | printf("\nEnter the number of elements:"); 10 | scanf("%d",&n); 11 | printf("\nEnter the elements of the array:\n"); 12 | for(int i=0;imintemp) 57 | { 58 | min=mintemp; 59 | } 60 | } 61 | } 62 | } 63 | /*OUTPUT: 64 | 65 | Enter the number of elements:5 66 | 67 | Enter the elements of the array: 68 | 12 69 | 23 70 | 1 71 | 78 72 | 35 73 | 74 | The min element is:1 75 | The max element is:78 76 | */ 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | -------------------------------------------------------------------------------- /SEARCHING/c or cpp/binarySearch.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement recursive Binary Search 2 | #include 3 | using namespace std; 4 | 5 | // A recursive binary search function. It returns location of x in given array arr[l..r] is present,otherwise -1 6 | int binarySearch(int arr[], int l, int r, int x) 7 | { 8 | if (r >= l) { 9 | int mid = l + (r - l) / 2; 10 | 11 | // If the element is present at the middle itself 12 | if (arr[mid] == x) 13 | return mid; 14 | 15 | // If element is smaller than mid, then it can only be present in left subarray 16 | if (arr[mid] > x) 17 | return binarySearch(arr, l, mid - 1, x); 18 | 19 | // Else the element can only be present in right subarray 20 | return binarySearch(arr, mid + 1, r, x); 21 | } 22 | 23 | // We reach here when element is not present in array 24 | return -1; 25 | } 26 | 27 | int main(void) 28 | { 29 | int arr[] = { 2, 3, 4, 10, 40 }; 30 | int x = 10; 31 | int n = sizeof(arr) / sizeof(arr[0]); 32 | int result = binarySearch(arr, 0, n - 1, x); 33 | (result == -1) ? cout << "Element is not present in array" 34 | : cout << "Element is present at index " << result; 35 | return 0; 36 | } 37 | -------------------------------------------------------------------------------- /SEARCHING/c or cpp/linear_search.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int array[100]; 6 | int i; 7 | int key; 8 | int n; 9 | int pos =0; 10 | cout<<"please enter the elements of array \n"; 11 | cin>>n; 12 | 13 | cout<<"please enter the array elements \n"; 14 | for (i=0;i>array[i]; 17 | cout<<"the elements of the array are \n"; 18 | for (i=0;i>key; 24 | cout<<"the inputed no is at position \n"; 25 | for(i=0;i= l) { 8 | int mid = l + (r - l) / 2; 9 | 10 | // If the element is present at the 11 | // middle itself 12 | if (arr[mid] == x) 13 | return mid; 14 | 15 | // If element is smaller than mid, then 16 | // it can only be present in left subarray 17 | if (arr[mid] > x) 18 | return binarySearch(arr, l, mid - 1, x); 19 | 20 | // Else the element can only be present 21 | // in right subarray 22 | return binarySearch(arr, mid + 1, r, x); 23 | } 24 | 25 | // We reach here when element is not present 26 | // in array 27 | return -1; 28 | } 29 | 30 | // Driver method to test above 31 | public static void main(String args[]) 32 | { 33 | BinarySearch ob = new BinarySearch(); 34 | int arr[] = { 2, 3, 4, 10, 40 }; 35 | int n = arr.length; 36 | int x = 10; 37 | int result = ob.binarySearch(arr, 0, n - 1, x); 38 | if (result == -1) 39 | System.out.println("Element not present"); 40 | else 41 | System.out.println("Element found at index " + result); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /SEARCHING/java/linear_search.java: -------------------------------------------------------------------------------- 1 | class GFG 2 | { 3 | public static int search(int arr[], int x) 4 | { 5 | int n = arr.length; 6 | for (int i = 0; i < n; i++) 7 | { 8 | if (arr[i] == x) 9 | return i; 10 | } 11 | return -1; 12 | } 13 | 14 | // Driver code 15 | public static void main(String args[]) 16 | { 17 | int arr[] = { 2, 3, 4, 10, 40 }; 18 | int x = 10; 19 | 20 | // Function call 21 | int result = search(arr, x); 22 | if (result == -1) 23 | System.out.print( 24 | "Element is not present in array"); 25 | else 26 | System.out.print("Element is present at index " 27 | + result); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /SEARCHING/py/Binary_search.py: -------------------------------------------------------------------------------- 1 | # Python Program to search a number using Binary search 2 | # Written by Lisha Ray 3 | 4 | # Function to implement Binary search 5 | def binary_search(lst,number_search):#lst is List: 6 | low = 0 7 | high = len(lst) - 1 8 | mid = 0 9 | 10 | while low <= high: 11 | 12 | mid = (high + low) // 2 13 | 14 | # Check if number_search is present at mid 15 | if lst[mid] < number_search : 16 | low = mid + 1 17 | 18 | # If number_search is greater, ignore left half 19 | elif lst[mid] > number_search : 20 | high = mid - 1 21 | 22 | # If number_search is smaller, ignore right half 23 | else: 24 | print("Element is present at ",mid+1," position in Sorted List." ) 25 | return 1 26 | 27 | # If we reach here, then the element was not present 28 | print("Element is not present.") 29 | 30 | 31 | lst = [int(item) for item in input("Enter the list items : ").split()] 32 | print("Sorted Array is") 33 | lst.sort() 34 | print(lst) 35 | number_search=int(input("Enter the number to be searched =")) 36 | binary_search(lst,number_search) 37 | 38 | 39 | #Enter the list items : 1 2 3 0 40 | #Sorted Array is 41 | #[0, 1, 2, 3] 42 | #Enter the number to be searched =3 43 | #Element is present at 4 position in Sorted List. -------------------------------------------------------------------------------- /SEARCHING/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Atharva Dhamale](https://github.com/adhamale2810) 8 | -------------------------------------------------------------------------------- /SEARCHING/py/binary_search.py: -------------------------------------------------------------------------------- 1 | 2 | # Returns index of x in arr if present, else -1 3 | def binary_search(arr, low, high, x): 4 | if high >= low: 5 | mid = (high + low) // 2 6 | # If element is present at the middle itself 7 | if arr[mid] == x: 8 | return mid 9 | elif arr[mid] > x: 10 | return binary_search(arr, low, mid - 1, x) 11 | else: 12 | return binary_search(arr, mid + 1, high, x) 13 | else: 14 | return -1 15 | 16 | # Array having element 17 | arr = [ 2, 3, 4, 10, 40 ] 18 | x = 10 19 | 20 | result = binary_search(arr, 0, len(arr)-1, x) 21 | 22 | if result != -1: 23 | print("Element is present at index", str(result)) 24 | else: 25 | print("Element is not present in array") 26 | -------------------------------------------------------------------------------- /SEARCHING/py/jumpsearch.py: -------------------------------------------------------------------------------- 1 | """Jump Search can only be used on a Sorted Array. 2 | Jump Search is technique that aims at doing lesser iterations for searching an element. 3 | It keeps searching the element at an interval depending on jump size. 4 | If the iteration reaches till end or the element appears to be greater than the element to find, 5 | then it use linear search from that index to the beginning of the array and gets the element.""" 6 | 7 | import math 8 | class JumpSearch: 9 | def __init__(self,arr): 10 | print("Enter Elements of array, press q to stop entering elements:") 11 | c = 1 12 | while c == 1: 13 | n = input() 14 | if n == 'q': 15 | c = 0 16 | break 17 | try: 18 | n = int(n) 19 | arr.append(n) 20 | except: 21 | print("Invalid Input") 22 | 23 | def sort(self,arr): 24 | n = len(arr) 25 | # looping through all elements of the array 26 | # using n-1 because at last iteration the loop will run even if the data is sorted 27 | # and increase time required unnecessarily 28 | for i in range(n-1): 29 | # using n-i-1 because the last element would be in the place after loop runs 30 | # one time so we can proceed with only remaining elements 31 | for j in range(n-i-1): 32 | if arr[j]>arr[j+1]: 33 | t = arr[j] 34 | arr[j] = arr[j+1] 35 | arr[j+1] = t 36 | print("Sorted Array:") 37 | print(arr) 38 | def jump(self,arr): 39 | c = 0 40 | n = len(arr) 41 | ns = int(input("Enter Number to search:")) 42 | js = int(math.sqrt(n))# Jump Size 43 | for i in range(0,n,js):# jump search till end of array 44 | if ns == arr[i]: 45 | print(str(ns)+" found at index "+str(i)) 46 | elif ns < arr[i]: 47 | bs = i; 48 | for j in range(n-1,0,-1):# linear search till start of array 49 | if ns == arr[j]: 50 | print(str(ns)+" found at index "+str(i)) 51 | c += 1 52 | if c == 0: 53 | print("Not Found") 54 | arr = list() 55 | obj = JumpSearch(arr) 56 | obj.sort(arr) 57 | obj.jump(arr) 58 | -------------------------------------------------------------------------------- /SEARCHING/py/linea_search.py: -------------------------------------------------------------------------------- 1 | def linear_search(a, x): 2 | for i in range(len(a)): 3 | if a[i] == x: 4 | return i 5 | return -1 6 | 7 | a = [1,4,7,9,14,17,39,56] 8 | x = 8 9 | y = 39 10 | 11 | print(linear_search(a,x)) 12 | print(linear_search(a,y)) 13 | -------------------------------------------------------------------------------- /SORTING/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Taniya Kulkarni](https://github.com/taniyask) 8 | - [Bhavesh Joshi](https://github.com/Wittty-Panda ) 9 | - [Ananthakrishnan Nair RS](https://github.com/akrish4) -------------------------------------------------------------------------------- /SORTING/c or cpp/MergeSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void merge_sort(int [],int ,int ); 5 | void merge(int [],int,int ,int ); 6 | 7 | int main() 8 | { 9 | int n; 10 | cout<<"Enter the size of the array"<>n; 12 | int a[n]; 13 | cout<<"Enter the elements in the array"<>a[i]; 17 | } 18 | 19 | cout<<"After sorting using merge sort"<::max();; 60 | R[n2+1]=numeric_limits::max();; 61 | int i=1, j=1; 62 | for(int k=p;k<=r;k++) 63 | { 64 | if(L[i]<=R[j]) 65 | { 66 | a[k]=L[i]; 67 | i=i+1; 68 | } 69 | else 70 | { 71 | a[k]=R[j]; 72 | j=j+1; 73 | } 74 | } 75 | } 76 | -------------------------------------------------------------------------------- /SORTING/c or cpp/QuickSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | 5 | int partition(int a[],int p,int r){ 6 | int x=a[r],temp; 7 | int i=p-1; 8 | for(int j=p;j> n; 36 | int a[n]; 37 | for (int i = 0; i < n; i++){ 38 | cin >> a[i];} 39 | quicksort(a,0,n-1); 40 | 41 | 42 | for (int i = 0; i < n; i++) 43 | cout << a[i] << " "; 44 | 45 | return 0; 46 | } 47 | -------------------------------------------------------------------------------- /SORTING/c or cpp/RadixSort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // Function to get the largest element from an array 5 | int getMax(int array[], int n) { 6 | int max = array[0]; 7 | for (int i = 1; i < n; i++) 8 | if (array[i] > max) 9 | max = array[i]; 10 | return max; 11 | } 12 | 13 | // Using counting sort to sort the elements in the basis of significant places 14 | void countingSort(int array[], int size, int place) { 15 | const int max = 10; 16 | int output[size]; 17 | int count[max]; 18 | 19 | for (int i = 0; i < max; ++i) 20 | count[i] = 0; 21 | 22 | // Calculate count of elements 23 | for (int i = 0; i < size; i++) 24 | count[(array[i] / place) % 10]++; 25 | 26 | // Calculate cumulative count 27 | for (int i = 1; i < max; i++) 28 | count[i] += count[i - 1]; 29 | 30 | // Place the elements in sorted order 31 | for (int i = size - 1; i >= 0; i--) { 32 | output[count[(array[i] / place) % 10] - 1] = array[i]; 33 | count[(array[i] / place) % 10]--; 34 | } 35 | 36 | for (int i = 0; i < size; i++) 37 | array[i] = output[i]; 38 | } 39 | 40 | // Main function to implement radix sort 41 | void radixsort(int array[], int size) { 42 | // Get maximum element 43 | int max = getMax(array, size); 44 | 45 | // Apply counting sort to sort elements based on place value. 46 | for (int place = 1; max / place > 0; place *= 10) 47 | countingSort(array, size, place); 48 | } 49 | 50 | // Print an array 51 | void printArray(int array[], int size) { 52 | int i; 53 | for (i = 0; i < size; i++) 54 | cout << array[i] << " "; 55 | cout << endl; 56 | } 57 | 58 | // Driver code 59 | int main() { 60 | int array[] = {121, 432, 564, 23, 1, 45, 788}; 61 | int n = sizeof(array) / sizeof(array[0]); 62 | radixsort(array, n); 63 | printArray(array, n); 64 | } -------------------------------------------------------------------------------- /SORTING/c or cpp/bubblesort.cpp: -------------------------------------------------------------------------------- 1 | // Bubble sort using template functions for both assending and descending 2 | 3 | #include 4 | using namespace std; 5 | 6 | template 7 | void assending(t list[], int n) 8 | { 9 | int i, j; 10 | t a; 11 | for (i = 0; i < n; ++i) 12 | { 13 | 14 | for (j = i + 1; j < n; ++j) 15 | { 16 | if (list[i] > list[j]) 17 | { 18 | a = list[i]; 19 | list[i] = list[j]; 20 | list[j] = a; 21 | } 22 | } 23 | } 24 | } 25 | 26 | template 27 | void descending(T list[], int n) 28 | { 29 | int i, j; 30 | T a; 31 | for (i = 0; i < n; ++i) 32 | { 33 | 34 | for (j = i + 1; j < n; ++j) 35 | { 36 | if (list[i] < list[j]) 37 | { 38 | a = list[i]; 39 | list[i] = list[j]; 40 | list[j] = a; 41 | } 42 | } 43 | } 44 | } 45 | 46 | 47 | int main() 48 | { 49 | int i, n, list[10]; 50 | float List[10]; 51 | 52 | cout<<"how many numbers you want to sort \n"; 53 | cin>>n; 54 | 55 | cout<<"Enter the numbers \n"; 56 | for (i = 0; i < n; ++i) 57 | cin>>list[i]; 58 | 59 | assending(list, n); 60 | 61 | cout<<"assending order is\n"; 62 | for (i = 0; i < n; ++i) 63 | cout<<"\t"<>List[i]; 76 | 77 | assending(List, n); 78 | 79 | cout<<"assending order of float is\n"; 80 | for (i = 0; i < n; ++i) 81 | cout<<"\t"< 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/c or cpp/selection_sort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | int n=0; 3 | int x[0]; 4 | int array[0]; 5 | int main(){ 6 | for(int x=0; xarray[y]) 13 | { 14 | index_of_min = y; 15 | } 16 | } 17 | int temp = array[x]; 18 | array[x] = array[index_of_min]; 19 | array[index_of_min] = temp; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /SORTING/countingsort.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | void print(long *vec, long n) { 5 | for(long i = 1; i<=n; i++) 6 | cout << vec[i] << " "; 7 | cout << "\n"; 8 | } 9 | 10 | long getMax(long vec[], long n) { 11 | long max = vec[1]; 12 | for(long i = 2; i<=n; i++) { 13 | if(vec[i] > max) 14 | max = vec[i]; 15 | } 16 | return max; 17 | } 18 | void countSort(long *vec, long n) { 19 | long output[n+1]; 20 | long max = getMax(vec, n); 21 | long count[max+1]; 22 | for(long i = 0; i<=max; i++) 23 | count[i] = 0; 24 | for(long i = 1; i <=n; i++) 25 | count[vec[i]]++; 26 | for(long i = 1; i<=max; i++) 27 | count[i] += count[i-1]; 28 | for(long i = n; i>=1; i--) { 29 | output[count[vec[i]]] = vec[i]; 30 | count[vec[i]] -= 1; 31 | } 32 | for(long i = 1; i<=n; i++) { 33 | vec[i] = output[i]; 34 | } 35 | } 36 | int main() { 37 | long n; 38 | cout << "Enter the size of array: "; 39 | cin >> n; 40 | long arr[n+1]; 41 | cout << "Enter elements:" << endl; 42 | for(long i = 1; i<=n; i++) 43 | cin >> arr[i]; 44 | cout << "Unsorted array: "; 45 | print(arr, n); 46 | countSort(arr, n); 47 | cout << "Sorted array: "; 48 | print(arr, n); 49 | } -------------------------------------------------------------------------------- /SORTING/java/BubbleSort.java: -------------------------------------------------------------------------------- 1 | public class BubbleSortExample { 2 | static void bubbleSort(int[] arr) { 3 | int n = arr.length; 4 | int temp = 0; 5 | for(int i=0; i < n; i++){ 6 | for(int j=1; j < (n-i); j++){ 7 | if(arr[j-1] > arr[j]){ 8 | //swap elements 9 | temp = arr[j-1]; 10 | arr[j-1] = arr[j]; 11 | arr[j] = temp; 12 | } 13 | 14 | } 15 | } 16 | 17 | } 18 | public static void main(String[] args) { 19 | int arr[] ={3,60,35,2,45,320,5}; 20 | 21 | System.out.println("Array Before Bubble Sort"); 22 | for(int i=0; i < arr.length; i++){ 23 | System.out.print(arr[i] + " "); 24 | } 25 | System.out.println(); 26 | 27 | bubbleSort(arr);//sorting array elements using bubble sort 28 | 29 | System.out.println("Array After Bubble Sort"); 30 | for(int i=0; i < arr.length; i++){ 31 | System.out.print(arr[i] + " "); 32 | } 33 | 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /SORTING/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Bhoomchai L.](https://github.com/bhoomchai) 8 | -------------------------------------------------------------------------------- /SORTING/java/InsertionSort.java: -------------------------------------------------------------------------------- 1 | import java.lang.reflect.Array; 2 | import java.util.Arrays; 3 | 4 | public class InsertionSort { 5 | 6 | static void insertionSort(int[] array) { 7 | for(int i=0; i< array.length; i++) { 8 | int tmp = array[i]; 9 | int j = i; 10 | while(j>0 && array[j-1] > tmp) { 11 | array[j] = array[j-1]; 12 | j--; 13 | } 14 | array[j] = tmp; 15 | } 16 | } 17 | 18 | public static void main(String args[]) { 19 | int[] array = new int[] {72,45,9,4,0,65,7,99,1}; 20 | System.out.println("Original list: " + Arrays.toString(array)); 21 | insertionSort(array); 22 | System.out.println("Sorted list: " + Arrays.toString(array)); 23 | } 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /SORTING/py/3-way quick sort .py: -------------------------------------------------------------------------------- 1 | # Uses python3 2 | import sys 3 | import random 4 | 5 | def partition3(a, l, r): 6 | #write your code here 7 | x, j, t = a[l], l, r 8 | i = j 9 | while i <= t: 10 | if a[i] < x: 11 | a[i],a[j] = a[j], a[i] 12 | j += 1 13 | elif a[i] > x: 14 | a[i],a[t] = a[t],a[i] 15 | t -= 1 16 | i -= 1 17 | i += 1 18 | return j,t 19 | 20 | 21 | 22 | 23 | def partition2(a, l, r): 24 | x = a[l] 25 | j = l 26 | for i in range(l + 1, r + 1): 27 | if a[i] <= x: 28 | j += 1 29 | a[i], a[j] = a[j], a[i] 30 | a[l], a[j] = a[j], a[l] 31 | return j 32 | 33 | 34 | def randomized_quick_sort(a, l, r): 35 | if l >= r: 36 | return 37 | k = random.randint(l, r) 38 | a[l], a[k] = a[k], a[l] 39 | #use partition3 40 | m1,m2 = partition3(a, l, r) 41 | randomized_quick_sort(a, l, m1 -1) 42 | randomized_quick_sort(a, m2 + 1, r) 43 | 44 | 45 | if __name__ == '__main__': 46 | input = sys.stdin.read() 47 | n, *a = list(map(int, input.split())) 48 | randomized_quick_sort(a, 0, n - 1) 49 | for x in a: 50 | print(x, end=' ') 51 | -------------------------------------------------------------------------------- /SORTING/py/BillCalculation.py: -------------------------------------------------------------------------------- 1 | class store: 2 | pro_code=[] 3 | name=[] 4 | price=[] 5 | 6 | 7 | def input_data(self): 8 | for i in range(5): 9 | self.pro_code.append(int(input("Enter the code:"))) 10 | self.name.append(input("Enter name:")) 11 | self.price.append(int(input("Enter price:"))) 12 | 13 | 14 | def display_data(self): 15 | print("pro_code \tname \t price") 16 | for i in range(5): 17 | print (self.pro_code[i],"\t\t",self.name[i],"\t\t",self.price[i]) 18 | 19 | 20 | def calculate_bill(self,qty): 21 | total=0 22 | for i in range(5): 23 | total=total+self.price[i]*qty[i] 24 | print("*****BILL*****") 25 | print("code\tname\tprice\tqty\tsubtotal") 26 | for i in range(5): 27 | print (self.pro_code[i],"\t",self.name[i],"\t",self.price[i],"\t",qty[i],"\t",qty[i]*self.price[i]) 28 | print ("Total:",total) 29 | 30 | 31 | s=store() 32 | s.input_data() 33 | s.display_data() 34 | q=[] 35 | print("Enter quantity:") 36 | for i in range(5): 37 | q.append(int(input())) 38 | s.calculate_bill(q) 39 | -------------------------------------------------------------------------------- /SORTING/py/Bubble Sort.py: -------------------------------------------------------------------------------- 1 | # Python Program to Implement Bubble Sort 2 | # Written by Lisha Ray 3 | 4 | # Function to calculate Factorial of a number 5 | def bubble_sort(lst): 6 | for i in range(len(lst)): 7 | for j in range(len(lst)-1): 8 | if lst[j] > lst[j+1]: 9 | temp=lst[j] 10 | lst[j]=lst[j+1] 11 | lst[j+1]=temp 12 | return lst 13 | 14 | lst = [int(item) for item in input("Enter the list items : ").split()] 15 | print("Sorted list = ",bubble_sort(lst)) 16 | 17 | #Output: 18 | #Enter the list items : 1 3 5 7 9 2 4 6 8 0 19 | #Sorted list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 20 | -------------------------------------------------------------------------------- /SORTING/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [KARAN WAGH](https://github.com/FlashTech-dev/) 8 | - [Lisha Ray](https://github.com/Lisharay4x3) 9 | - [Dhimas Bayu](https://github.com/bailram) 10 | - [Pijush Barman](https://github.com/Pijush-Beyond) 11 | -------------------------------------------------------------------------------- /SORTING/py/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 | def heapify(arr, n, i): 6 | largest = i # Initialize largest as root 7 | l = 2 * i + 1 # left = 2*i + 1 8 | r = 2 * i + 2 # right = 2*i + 2 9 | 10 | # See if left child of root exists and is 11 | # greater than root 12 | if l < n and arr[i] < arr[l]: 13 | largest = l 14 | 15 | # See if right child of root exists and is 16 | # greater than root 17 | if r < n and arr[largest] < arr[r]: 18 | largest = r 19 | 20 | # Change root, if needed 21 | if largest != i: 22 | arr[i],arr[largest] = arr[largest],arr[i] # swap 23 | 24 | # Heapify the root. 25 | heapify(arr, n, largest) 26 | 27 | # The main function to sort an array of given size 28 | def heapSort(arr): 29 | n = len(arr) 30 | 31 | # Build a maxheap. 32 | for i in range(n//2 - 1, -1, -1): 33 | heapify(arr, n, i) 34 | 35 | # One by one extract elements 36 | for i in range(n-1, 0, -1): 37 | arr[i], arr[0] = arr[0], arr[i] # swap 38 | heapify(arr, i, 0) 39 | 40 | # Driver code to test above 41 | arr = [ 12, 11, 13, 5, 6, 7] 42 | heapSort(arr) 43 | n = len(arr) 44 | print ("Sorted array is") 45 | for i in range(n): 46 | print ("%d" %arr[i]), 47 | # This code is contributed by Mohit Kumra 48 | -------------------------------------------------------------------------------- /SORTING/py/MergeSort.py: -------------------------------------------------------------------------------- 1 | # Python program to implementation of Merge Sort Algorithm 2 | # Time Complexity : Ω(n log(n)) 3 | 4 | 5 | def mergeSort(array): 6 | if (len(array) > 1): 7 | mid = len(array) // 2 8 | # Dividing the array elements into two sub arrays 9 | left = array[:mid] 10 | right = array[mid:] 11 | 12 | #Sorting Two Half of arrays seperately 13 | mergeSort(left) 14 | mergeSort(right) 15 | 16 | i = j = k = 0 17 | 18 | # Copy data to temp arrays L[] and R[] 19 | while (i < len(left) and j < len(right)): 20 | if (left[i] < right[j]): 21 | array[k] = left[i] 22 | i += 1 23 | else: 24 | array[k] = right[j] 25 | j += 1 26 | k += 1 27 | 28 | # Checking if any element was left 29 | while (i < len(left)): 30 | array[k] = left[i] 31 | i += 1 32 | k += 1 33 | 34 | while (j < len(right)): 35 | array[k] = right[j] 36 | j += 1 37 | k += 1 38 | 39 | 40 | 41 | # driver code for testing 42 | if __name__ == "__main__": 43 | array = [ 4, 10, 15, 35, -30, 23, -9, 50, 0] 44 | 45 | print ("Before Sorting : ", array) 46 | mergeSort(array) 47 | print ("After Sorting : ", array) 48 | 49 | -------------------------------------------------------------------------------- /SORTING/py/QuickSort.py: -------------------------------------------------------------------------------- 1 | def partition(arr, low, high): 2 | i = (low-1) 3 | pivot = arr[high] 4 | 5 | for j in range(low, high): 6 | 7 | if arr[j] <= pivot: 8 | i = i+1 9 | arr[i], arr[j] = arr[j], arr[i] 10 | 11 | arr[i+1], arr[high] = arr[high], arr[i+1] 12 | return (i+1) 13 | 14 | def quickSort(arr, low, high): 15 | if len(arr) == 1: 16 | return arr 17 | if low < high: 18 | pi = partition(arr, low, high) 19 | quickSort(arr, low, pi-1) 20 | quickSort(arr, pi+1, high) 21 | 22 | 23 | n = int(input("Enter number of elements : ")) 24 | arr = list(map(int,input("Enter the numbers : ").strip().split()))[:n] 25 | quickSort(arr, 0, n-1) 26 | print("Sorted array is:",arr) 27 | 28 | 29 | -------------------------------------------------------------------------------- /SORTING/py/SelectionSort.py: -------------------------------------------------------------------------------- 1 | def selection_sort(input_list): 2 | 3 | for idx in range(len(input_list)): 4 | 5 | min_idx = idx 6 | for j in range( idx +1, len(input_list)): 7 | if input_list[min_idx] > input_list[j]: 8 | min_idx = j 9 | # Swap the minimum value with the compared value 10 | 11 | input_list[idx], input_list[min_idx] = input_list[min_idx], input_list[idx] 12 | 13 | 14 | l = [19,2,31,45,30,11,121,27] 15 | selection_sort(l) 16 | print(l) 17 | -------------------------------------------------------------------------------- /SORTING/py/pybogo.py: -------------------------------------------------------------------------------- 1 | import random 2 | from random import randit, shuffle 3 | def bosort(a): 4 | iter=0 5 | while not is_sorted(a): 6 | shuffle(a) 7 | iter=iter+1 8 | return iter,a 9 | def sorted(a): 10 | for i in xrange (1, len(a)): 11 | if a[i] 5 | #include 6 | #include "stack.h" 7 | 8 | //Funtion required to convert infix to postfix 9 | int precedence(char character); 10 | void infix_to_postfix(char expression[]); 11 | 12 | //Main function 13 | void main() 14 | { 15 | char expression[100]; 16 | printf("Enter your infix expression: "); 17 | scanf(" %s", expression); 18 | infix_to_postfix(expression); 19 | } 20 | 21 | //Function to check precedence of the operator 22 | int precedence(char character) 23 | { 24 | if(character=='^') //Highest precedence 25 | return 3; 26 | 27 | if(character == '*' || character == '/') 28 | return 2; 29 | 30 | else if(character == '+' || character == '-') //Lowest Precedence 31 | return 1; 32 | 33 | else 34 | return 0; 35 | } 36 | 37 | //Funtion to convert infix to postfix 38 | void infix_to_postfix(char expression[]) 39 | { 40 | int i; 41 | struct char_stack stk; 42 | stk.char_push = char_push; 43 | stk.char_pop = char_pop; 44 | stk.char_display = char_display; 45 | stk.top = -1; 46 | strncat(expression,"$",2); 47 | printf("\nThe expression in postfix is:\n"); 48 | for (i=0; expression[i]!='$'; i++) 49 | { 50 | if (isalpha(expression[i])) 51 | printf(" %c",expression[i]); 52 | 53 | else if (expression[i] == '(') 54 | stk.char_push(expression[i], &stk); 55 | 56 | else if (expression[i] == ')') 57 | { 58 | while( stk.arr[stk.top] != '(') 59 | { 60 | printf(" %c", stk.arr[stk.top]); 61 | stk.char_pop(&stk); 62 | } 63 | stk.char_pop(&stk); 64 | } 65 | 66 | else 67 | { 68 | while(precedence(stk.arr[stk.top]) >= precedence(expression[i])) 69 | { 70 | printf(" %c", stk.arr[stk.top]); 71 | stk.char_pop(&stk); 72 | } 73 | stk.char_push(expression[i], &stk); 74 | } 75 | } 76 | 77 | while(stk.top != -1) 78 | { 79 | printf(" %c", stk.arr[stk.top]); 80 | stk.char_pop(&stk); 81 | } 82 | printf("\n"); 83 | 84 | } -------------------------------------------------------------------------------- /STACK AND QUEUES/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Taniya Kulkarni](https://github.com/taniyask) 8 | -------------------------------------------------------------------------------- /STACK AND QUEUES/c or cpp/Queue_ADT.c: -------------------------------------------------------------------------------- 1 | //Program to implement queue ADT using singly linked list 2 | //Author: Taniya Kulkarni 3 | 4 | #include 5 | #include "COE19B046_list.h" 6 | 7 | 8 | void main() 9 | { 10 | int choice; 11 | create_queue(); 12 | do{ 13 | printf("\nChoose what operation you wish to do: \n 1. Enqueue \n 2. Display \n 3. Dequeue \n 0. Exit \n Enter choice: "); 14 | scanf("%d", &choice); 15 | switch(choice) 16 | { 17 | case 1: //Option to Enqueue 18 | { 19 | int element; 20 | printf("\nEnter number you wish to enqueue:"); 21 | scanf("%d", &element); 22 | enqueue(element); 23 | break; 24 | } 25 | case 2: //Option to display elements in queue 26 | { 27 | queue_display(); 28 | break; 29 | } 30 | case 3: //Option to Dequeue 31 | { 32 | dequeue(); 33 | break; 34 | } 35 | default: 36 | { 37 | if(choice!=0) 38 | { 39 | printf("\n Wrong Choice!!\n"); 40 | } 41 | } 42 | 43 | } 44 | }while(choice!=0); 45 | } 46 | -------------------------------------------------------------------------------- /STACK AND QUEUES/c or cpp/Stack_ADT.c: -------------------------------------------------------------------------------- 1 | //Program to implement stack ADT using singly linked list 2 | //Author: Taniya Kulkarni 3 | 4 | #include 5 | #include "COE19B046_list.h" 6 | 7 | void main() 8 | { 9 | int choice; 10 | create_stack(); 11 | do{ 12 | printf("\nChoose what operation you wish to do: \n 1. Push \n 2. Display \n 3. Pop \n 0. Exit \n Enter choice: "); 13 | scanf("%d", &choice); 14 | switch(choice) 15 | { 16 | case 1: //Option to Push elements into stack 17 | { 18 | int element; 19 | printf("\nEnter number you wish to push:"); 20 | scanf("%d", &element); 21 | push(element); 22 | break; 23 | } 24 | case 2: //Option to Display elements in stack 25 | { 26 | stack_display(); 27 | break; 28 | } 29 | case 3: //Option to Pop elements from stack 30 | { 31 | pop(); 32 | break; 33 | } 34 | default: 35 | { 36 | if(choice!=0) 37 | { 38 | printf("\n Wrong Choice!!\n"); 39 | } 40 | } 41 | 42 | } 43 | }while(choice!=0); 44 | } 45 | -------------------------------------------------------------------------------- /STACK AND QUEUES/c or cpp/Stack_Operations.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int stack[100],n=100,top=-1; 5 | void push(int val) { 6 | if(top>=n-1) 7 | cout<<"Stack Overflow"<=0) { 23 | cout<<"Stack elements are:"; 24 | for(int i=top; i>=0; i--) 25 | cout<>ch; 39 | switch(ch) { 40 | case 1: { 41 | cout<<"Enter value to be pushed:"<>val; 43 | push(val); 44 | break; 45 | } 46 | case 2: { 47 | pop(); 48 | break; 49 | } 50 | case 3: { 51 | display(); 52 | break; 53 | } 54 | case 4: { 55 | cout<<"Exit"< 2 | using namespace std; 3 | class Stack{ 4 | int stack[100], n = 100, top = -1; 5 | public: 6 | void push(int val); 7 | void pop(); 8 | void display(); 9 | }; 10 | 11 | void Stack::push(int val) { 12 | if(top >= n-1) 13 | cout<<"Stack Overflow"<= 0) { 29 | cout<<"Stack elements are:"; 30 | for(int i = top; i>= 0; i--) 31 | cout<>ch; 46 | switch(ch) { 47 | case 1: { 48 | cout<<"Enter value to be pushed:"<>val; 50 | s.push(val); 51 | break; 52 | } 53 | case 2: { 54 | s.pop(); 55 | break; 56 | } 57 | case 3: { 58 | s.display(); 59 | break; 60 | } 61 | case 4: { 62 | cout<<"Exit"<= prec[token]): 39 | postfix_exp.append(data_stack.pop()) 40 | data_stack.push(token) 41 | 42 | # Any operators still on the stack can be removed and appended to the end of the output list. 43 | while not data_stack.is_empty(): 44 | postfix_exp.append(data_stack.pop()) 45 | 46 | return " ".join(postfix_exp) 47 | 48 | # Testing 49 | print(InfixToPostfix("A * B + C * D")) 50 | print(InfixToPostfix("( A + B ) * C - ( D - E ) * ( F + G )")) -------------------------------------------------------------------------------- /STACK AND QUEUES/py/queue.py: -------------------------------------------------------------------------------- 1 | # Python program to 2 | # demonstrate implementation of 3 | # queue using queue module 4 | 5 | 6 | from queue import Queue 7 | 8 | # Initializing a queue 9 | q = Queue(maxsize = 3) 10 | 11 | # qsize() give the maxsize 12 | # of the Queue 13 | print(q.qsize()) 14 | 15 | # Adding of element to queue 16 | q.put('a') 17 | q.put('b') 18 | q.put('c') 19 | 20 | # Return Boolean for Full 21 | # Queue 22 | print("\nFull: ", q.full()) 23 | 24 | # Removing element from queue 25 | print("\nElements dequeued from the queue") 26 | print(q.get()) 27 | print(q.get()) 28 | print(q.get()) 29 | 30 | # Return Boolean for Empty 31 | # Queue 32 | print("\nEmpty: ", q.empty()) 33 | 34 | q.put(1) 35 | print("\nEmpty: ", q.empty()) 36 | print("Full: ", q.full()) 37 | 38 | # This would result into Infinite 39 | # Loop as the Queue is empty. 40 | # print(q.get()) 41 | -------------------------------------------------------------------------------- /STRINGS/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | - [Alan Biju Gregory](https://github.com/bijualan669) 8 | -------------------------------------------------------------------------------- /STRINGS/c or cpp/Palindrome.c: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | #include 4 | 5 | // A function to check if a string str is palindrome 6 | void isPalindrome(char str[]) 7 | { 8 | // Start from leftmost and rightmost corners of str 9 | int l = 0; 10 | int h = strlen(str) - 1; 11 | 12 | // Keep comparing characters while they are same 13 | while (h > l) 14 | { 15 | if (str[l++] != str[h--]) 16 | { 17 | printf("%s is Not Palindrome", str); 18 | return; 19 | } 20 | } 21 | printf("%s is palindrome", str); 22 | } 23 | 24 | // Driver program to test above function 25 | int main() 26 | { 27 | isPalindrome("abba"); 28 | isPalindrome("abbccbba"); 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /STRINGS/c or cpp/encodestring.cpp: -------------------------------------------------------------------------------- 1 | /*This program converts a normal string into a encode string*/ 2 | 3 | #include 4 | #include 5 | using namespace std; 6 | int main() 7 | { 8 | string decode = "abcdefhijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; 9 | string code = "ZYXWVUTSRQPONMLKJIHGFEDCBAzyxwvutsrqponmlkjihfedcba"; 10 | string input; 11 | string output=""; 12 | cout<<"Enter a String:"<>input; 14 | int l = input.length(); 15 | for(int i=0;i str: 2 | """ 3 | Reverses words in a given string 4 | >>> reverse_words("I love Python") 5 | 'Python love I' 6 | >>> reverse_words("I Love Python") 7 | 'Python Love I' 8 | """ 9 | return " ".join(input_str.split()[::-1]) 10 | 11 | 12 | if __name__ == "__main__": 13 | import doctest 14 | 15 | doctest.testmod() -------------------------------------------------------------------------------- /TREES/c or cpp/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | - [Dhruvil Shah](https://github.com/d-s-2803) 5 | - [Gaurav Verma](https://github.com/thegauravverma) 6 | - [Bhavesh Joshi](https://github.com/Wittty-Panda ) 7 | - [Mayur Narkhede](https://github.com/PrinceMayur007) 8 | - [Aniket Prabhakar](https://github.com/aniketprabhakar) 9 | 10 | -------------------------------------------------------------------------------- /TREES/c or cpp/OBST.CPP: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define max 20 5 | 6 | int i,j,k,n,min,r[max][max]; 7 | float p[max],q[max],w[max][max],c[max][max]; 8 | char leaf[max]; 9 | void OBST(); 10 | void print(int,int); 11 | void print_tab(); 12 | void main() 13 | { 14 | clrscr(); 15 | cout<<"\nEnter no. of nodes :"; 16 | cin>>n; 17 | cout<<"\nEnter successful probability :"; 18 | for(i=1;i<=n;i++) 19 | { 20 | cin>>p[i]; 21 | } 22 | cout<<"\nEnter unsuccessful probability :"; 23 | for(i=0;i<=n;i++) 24 | { 25 | cin>>q[i]; 26 | } 27 | OBST(); 28 | print_tab(); 29 | //print(0,n); 30 | getch(); 31 | } 32 | void OBST() 33 | { 34 | for(i=0;ic[j][k-1]+c[k][j+i]) 56 | { 57 | c[j][j+i]=c[j][k-1]+c[k][j+i]; 58 | r[j][j+i]=k; 59 | } 60 | } 61 | c[j][j+i]+=w[j][j+i]; 62 | } 63 | } 64 | } 65 | void print_tab() 66 | { 67 | for(i=0;i<=n;i++) 68 | cout<<"w"< 4 | #include 5 | #include 6 | 7 | struct node 8 | { 9 | int data; 10 | struct node *left; 11 | struct node *right; 12 | }; 13 | 14 | 15 | struct node* newNode(int data) 16 | { 17 | 18 | struct node* node = (struct node*)malloc(sizeof(struct node)); 19 | 20 | 21 | node->data = data; 22 | 23 | 24 | node->left = NULL; 25 | node->right = NULL; 26 | return(node); 27 | } 28 | 29 | insert(int key, struct node **leaf) 30 | { 31 | if (*leaf == 0) 32 | { 33 | *leaf = (struct node*) malloc(sizeof(struct node)); 34 | (*leaf)->data = key; 35 | /* initialize the children to null */ 36 | (*leaf)->left = 0; 37 | (*leaf)->right = 0; 38 | } 39 | else if (key <= (*leaf)->data) 40 | { 41 | insert(key, &(*leaf)->left); 42 | } 43 | else if (key >(*leaf)->data) 44 | { 45 | insert(key, &(*leaf)->right); 46 | } 47 | } 48 | 49 | int main() 50 | { 51 | srand(time(NULL)); 52 | /*create root*/ 53 | struct node *root = NULL; 54 | 55 | int tree_size = 100; 56 | int new_leaf_value; 57 | 58 | root = newNode(50); 59 | for (int i = 1; i <= tree_size; i++) 60 | { 61 | new_leaf_value = rand() % 100; 62 | insert(new_leaf_value, &root); 63 | } 64 | getchar(); 65 | return 0; 66 | } -------------------------------------------------------------------------------- /TREES/c or cpp/bstFromSortedArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *left; 8 | struct Node *right; 9 | 10 | Node(int value) 11 | { 12 | data = value; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | Node *sortedArrayToBST(int arr[], int start, int end) 19 | { 20 | if (start > end) 21 | { 22 | return NULL; 23 | } 24 | int mid = (start + end) / 2; 25 | Node *root = new Node(arr[mid]); 26 | root->left = sortedArrayToBST(arr, start, mid - 1); 27 | root->right = sortedArrayToBST(arr, mid + 1, end); 28 | return root; 29 | } 30 | 31 | void preorderPrint(Node *root) 32 | { 33 | if (root == NULL) 34 | { 35 | return; 36 | } 37 | cout << root->data << " "; 38 | preorderPrint(root->left); 39 | preorderPrint(root->right); 40 | } 41 | 42 | void inorderPrint(Node *root) 43 | { 44 | if (root == NULL) 45 | { 46 | return; 47 | } 48 | inorderPrint(root->left); 49 | cout << root->data << " "; 50 | inorderPrint(root->right); 51 | } 52 | 53 | int main() 54 | { 55 | int sorted_array[50]; 56 | int n; 57 | cin >> n; 58 | for (int i = 0; i < n; i++) 59 | { 60 | cin >> sorted_array[i]; 61 | } 62 | Node *root = sortedArrayToBST(sorted_array, 0, n - 1); 63 | cout << "Preorder print: "; 64 | preorderPrint(root); 65 | cout << "\nInorder traversal: "; 66 | inorderPrint(root); 67 | return 0; 68 | } 69 | -------------------------------------------------------------------------------- /TREES/c or cpp/treePreIn.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | Node *left; 8 | Node *right; 9 | 10 | Node(int val) 11 | { 12 | data = val; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | int search(int inorder[], int start, int end, int curr) 19 | { 20 | for (int i = start; i <= end; i++) 21 | { 22 | if (inorder[i] == curr) 23 | { 24 | return i; 25 | } 26 | } 27 | return -1; 28 | } 29 | Node *buildTree(int preorder[], int inorder[], int start, int end) 30 | { 31 | static int idx = 0; 32 | 33 | if (start > end) 34 | { 35 | return NULL; 36 | } 37 | int curr = preorder[idx]; 38 | idx++; 39 | Node *node = new Node(curr); 40 | if (start == end) 41 | { 42 | return node; 43 | } 44 | int pos = search(inorder, start, end, curr); 45 | node->left = buildTree(preorder, inorder, start, pos - 1); 46 | node->left = buildTree(preorder, inorder, pos + 1, end); 47 | 48 | return node; 49 | } 50 | 51 | void inorderPrint(Node *root) 52 | { 53 | if (root == NULL) 54 | { 55 | return; 56 | } 57 | inorderPrint(root->left); 58 | cout << root->data << " "; 59 | inorderPrint(root->right); 60 | } 61 | 62 | int main() 63 | { 64 | int preorder[] = {1, 2, 4, 3, 5}; 65 | int inorder[] = {4, 2, 1, 5, 3}; 66 | 67 | Node *root = buildTree(preorder, inorder, 0, 4); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /TREES/java/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /TREES/py/Contributors.md: -------------------------------------------------------------------------------- 1 | # Contributors 2 | 3 | If you have contributed to this repository, kindly add your username here 4 | 5 | - [Dhruvil Shah](https://github.com/d-s-2803) 6 | - [Gaurav Verma](https://github.com/thegauravverma) 7 | -------------------------------------------------------------------------------- /TREES/treePreIn.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | Node *left; 8 | Node *right; 9 | 10 | Node(int val) 11 | { 12 | data = val; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | int search(int inorder[], int start, int end, int curr) 19 | { 20 | for (int i = start; i <= end; i++) 21 | { 22 | if (inorder[i] == curr) 23 | { 24 | return i; 25 | } 26 | } 27 | return -1; 28 | } 29 | Node *buildTree(int preorder[], int inorder[], int start, int end) 30 | { 31 | static int idx = 0; 32 | 33 | if (start > end) 34 | { 35 | return NULL; 36 | } 37 | int curr = preorder[idx]; 38 | idx++; 39 | Node *node = new Node(curr); 40 | if (start == end) 41 | { 42 | return node; 43 | } 44 | int pos = search(inorder, start, end, curr); 45 | node->left = buildTree(preorder, inorder, start, pos - 1); 46 | node->left = buildTree(preorder, inorder, pos + 1, end); 47 | 48 | return node; 49 | } 50 | 51 | void inorderPrint(Node *root) 52 | { 53 | if (root == NULL) 54 | { 55 | return; 56 | } 57 | inorderPrint(root->left); 58 | cout << root->data << " "; 59 | inorderPrint(root->right); 60 | } 61 | 62 | int main() 63 | { 64 | int preorder[] = {1, 2, 4, 3, 5}; 65 | int inorder[] = {4, 2, 1, 5, 3}; 66 | 67 | Node *root = buildTree(preorder, inorder, 0, 4); 68 | return 0; 69 | } -------------------------------------------------------------------------------- /bstFromSortedArr.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | struct Node 5 | { 6 | int data; 7 | struct Node *left; 8 | struct Node *right; 9 | 10 | Node(int value) 11 | { 12 | data = value; 13 | left = NULL; 14 | right = NULL; 15 | } 16 | }; 17 | 18 | Node *sortedArrayToBST(int arr[], int start, int end) 19 | { 20 | if (start > end) 21 | { 22 | return NULL; 23 | } 24 | int mid = (start + end) / 2; 25 | Node *root = new Node(arr[mid]); 26 | root->left = sortedArrayToBST(arr, start, mid - 1); 27 | root->right = sortedArrayToBST(arr, mid + 1, end); 28 | return root; 29 | } 30 | 31 | void preorderPrint(Node *root) 32 | { 33 | if (root == NULL) 34 | { 35 | return; 36 | } 37 | cout << root->data << " "; 38 | preorderPrint(root->left); 39 | preorderPrint(root->right); 40 | } 41 | 42 | void inorderPrint(Node *root) 43 | { 44 | if (root == NULL) 45 | { 46 | return; 47 | } 48 | inorderPrint(root->left); 49 | cout << root->data << " "; 50 | inorderPrint(root->right); 51 | } 52 | 53 | int main() 54 | { 55 | int sorted_array[50]; 56 | int n; 57 | cin >> n; 58 | for (int i = 0; i < n; i++) 59 | { 60 | cin >> sorted_array[i]; 61 | } 62 | Node *root = sortedArrayToBST(sorted_array, 0, n - 1); 63 | cout << "Preorder print: "; 64 | preorderPrint(root); 65 | cout << "\nInorder traversal: "; 66 | inorderPrint(root); 67 | return 0; 68 | } 69 | --------------------------------------------------------------------------------