mirror of
https://github.com/TheAlgorithms/C-Plus-Plus.git
synced 2026-02-13 07:25:42 +08:00
Merge branch 'master' into patch-1
This commit is contained in:
33
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
33
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,33 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve. Report bugs found while using the project
|
||||
title: "[BUG]"
|
||||
labels: bug
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--- Provide a general summary of the issue in the Title above -->
|
||||
|
||||
## Description
|
||||
<!--- Provide a more detailed introduction to the issue itself, and why you consider it to be a bug -->
|
||||
|
||||
## Expected Behavior
|
||||
<!--- Tell us what should happen -->
|
||||
|
||||
## Actual Behavior
|
||||
<!--- Tell us what happens instead -->
|
||||
|
||||
## Possible Fix
|
||||
<!--- Not obligatory, but suggest a fix or reason for the bug -->
|
||||
|
||||
## Steps to Reproduce
|
||||
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
|
||||
<!--- reproduce this bug. Include code to reproduce, if relevant -->
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
4.
|
||||
|
||||
## Context
|
||||
<!--- How has this bug affected you? What were you trying to accomplish? -->
|
||||
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
20
.github/ISSUE_TEMPLATE/feature_request.md
vendored
Normal file
@@ -0,0 +1,20 @@
|
||||
---
|
||||
name: Feature request
|
||||
about: Suggest features, propose improvements, discuss new ideas.
|
||||
title: "[FEATURE]"
|
||||
labels: enhancement
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
<!--- Provide a general summary of the issue in the Title above -->
|
||||
|
||||
## Detailed Description
|
||||
<!--- Provide a detailed description of the change or addition you are proposing -->
|
||||
|
||||
## Context
|
||||
<!--- Why is this change important to you? How would you use it? -->
|
||||
<!--- How can it benefit other users? -->
|
||||
|
||||
## Possible Implementation
|
||||
<!--- Not obligatory, but suggest an idea for implementing addition or change -->
|
||||
21
.github/pull_request_template.md
vendored
Normal file
21
.github/pull_request_template.md
vendored
Normal file
@@ -0,0 +1,21 @@
|
||||
#### Description of Change
|
||||
<!--
|
||||
Thank you for your Pull Request. Please provide a description above and review
|
||||
the requirements below.
|
||||
|
||||
Contributors guide: https://github.com/TheAlgorithms/C-Plus-Plus/CONTRIBUTION.md
|
||||
-->
|
||||
|
||||
#### Checklist
|
||||
<!-- Remove items that do not apply. For completed items, change [ ] to [x]. -->
|
||||
|
||||
- [ ] Added description of change
|
||||
- [ ] Added file name matches [File name guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#New-File-Name-guidelines)
|
||||
- [ ] Added tests and example, test must pass
|
||||
- [ ] Relevant documentation/comments is changed or added
|
||||
- [ ] PR title follows semantic [commit guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md#Commit-Guidelines)
|
||||
- [ ] Search previous suggestions before making a new one, as yours may be a duplicate.
|
||||
- [ ] Sort by alphabetical order
|
||||
- [ ] I acknowledge that all my contributions will be made under the project's license.
|
||||
|
||||
Notes: <!-- Please add a one-line description for developers or pull request viewers -->
|
||||
13
.github/workflows/cpplint.yml
vendored
Normal file
13
.github/workflows/cpplint.yml
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
name: cpplint
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: actions/setup-python@v1
|
||||
- run: pip install cpplint
|
||||
# - run: cpplint --filter= # print out all cpplint rules
|
||||
- run: cpplint --recursive . || true # all issues to be fixed
|
||||
# TODO: Remove each filter one at a time and fix those failures
|
||||
- run: cpplint --filter=-build,-legal,-readability,-runtime,-whitespace --recursive .
|
||||
64
.github/workflows/cpplint_modified_files.yml
vendored
Normal file
64
.github/workflows/cpplint_modified_files.yml
vendored
Normal file
@@ -0,0 +1,64 @@
|
||||
# GitHub Action that enables a repo to achieve gradual compliance with cpplint by
|
||||
# linting only those files that have been added or modified (vs. origin/master).
|
||||
# 1. runs cpplint only on those files that have been modified vs. origin/master.
|
||||
# 2. compiles with g++ only those files that have been modified vs. origin/master.
|
||||
# 3. other optional filepath verifications may be commented out at the end of this file.
|
||||
# From: https://github.com/cpplint/GitHub-Action-for-cpplint
|
||||
|
||||
name: cpplint_modified_files
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
cpplint_modified_files:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v1 # v2 is broken for git diff
|
||||
- uses: actions/setup-python@v1
|
||||
- run: python -m pip install cpplint
|
||||
- run: git remote -v
|
||||
- run: git branch
|
||||
- run: git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
|
||||
- run: git diff --diff-filter=dr --name-only origin/master > git_diff.txt
|
||||
- name: cpplint_modified_files
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
print("Python {}.{}.{}".format(*sys.version_info)) # Python 3.8
|
||||
with open("git_diff.txt") as in_file:
|
||||
modified_files = sorted(in_file.read().splitlines())
|
||||
print("{} files were modified.".format(len(modified_files)))
|
||||
|
||||
cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split())
|
||||
cpp_files = [file for file in modified_files if file.lower().endswith(cpp_exts)]
|
||||
print(f"{len(cpp_files)} C++ files were modified.")
|
||||
if not cpp_files:
|
||||
sys.exit(0)
|
||||
|
||||
print("cpplint:")
|
||||
subprocess.run(["cpplint", "--filter=-legal/copyright"] + cpp_files, check=True, text=True)
|
||||
|
||||
print("g++:")
|
||||
# compile_exts = tuple(".c .c++ .cc .cpp .cu .cxx".split())
|
||||
# compile_files = [file for file in cpp_files if file.lower().endswith(compile_exts)]
|
||||
subprocess.run(["g++"] + cpp_files, check=True, text=True)
|
||||
|
||||
upper_files = [file for file in cpp_files if file != file.lower()]
|
||||
if upper_files:
|
||||
print(f"{len(upper_files)} files contain uppercase characters:")
|
||||
print("\n".join(upper_files) + "\n")
|
||||
|
||||
space_files = [file for file in cpp_files if " " in file or "-" in file]
|
||||
if space_files:
|
||||
print(f"{len(space_files)} files contain space or dash characters:")
|
||||
print("\n".join(space_files) + "\n")
|
||||
|
||||
nodir_files = [file for file in cpp_files if file.count(os.sep) != 1]
|
||||
if nodir_files:
|
||||
print(f"{len(nodir_files)} files are not in one and only one directory:")
|
||||
print("\n".join(nodir_files) + "\n")
|
||||
|
||||
bad_files = len(upper_files + space_files + nodir_files)
|
||||
if bad_files:
|
||||
sys.exit(bad_files)
|
||||
68
.github/workflows/update_directory_md.yml
vendored
Normal file
68
.github/workflows/update_directory_md.yml
vendored
Normal file
@@ -0,0 +1,68 @@
|
||||
# This GitHub Action updates the DIRECTORY.md file (if needed) when doing a git push
|
||||
name: update_directory_md
|
||||
on: [push]
|
||||
jobs:
|
||||
update_directory_md:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-python@v1
|
||||
- name: update_directory_md
|
||||
shell: python
|
||||
run: |
|
||||
import os
|
||||
from typing import Iterator
|
||||
|
||||
URL_BASE = "https://github.com/TheAlgorithms/C-Plus-Plus/blob/master"
|
||||
g_output = []
|
||||
|
||||
|
||||
def good_filepaths(top_dir: str = ".") -> Iterator[str]:
|
||||
cpp_exts = tuple(".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx".split())
|
||||
for dirpath, dirnames, filenames in os.walk(top_dir):
|
||||
dirnames[:] = [d for d in dirnames if d[0] not in "._"]
|
||||
for filename in filenames:
|
||||
if os.path.splitext(filename)[1].lower() in cpp_exts:
|
||||
yield os.path.join(dirpath, filename).lstrip("./")
|
||||
|
||||
|
||||
def md_prefix(i):
|
||||
return f"{i * ' '}*" if i else "\n##"
|
||||
|
||||
|
||||
def print_path(old_path: str, new_path: str) -> str:
|
||||
global g_output
|
||||
old_parts = old_path.split(os.sep)
|
||||
for i, new_part in enumerate(new_path.split(os.sep)):
|
||||
if i + 1 > len(old_parts) or old_parts[i] != new_part:
|
||||
if new_part:
|
||||
g_output.append(f"{md_prefix(i)} {new_part.replace('_', ' ').title()}")
|
||||
return new_path
|
||||
|
||||
|
||||
def build_directory_md(top_dir: str = ".") -> str:
|
||||
global g_output
|
||||
old_path = ""
|
||||
for filepath in sorted(good_filepaths(), key=str.lower):
|
||||
filepath, filename = os.path.split(filepath)
|
||||
if filepath != old_path:
|
||||
old_path = print_path(old_path, filepath)
|
||||
indent = (filepath.count(os.sep) + 1) if filepath else 0
|
||||
url = "/".join((URL_BASE, filepath, filename)).replace(" ", "%20")
|
||||
filename = os.path.splitext(filename.replace("_", " ").title())[0]
|
||||
g_output.append(f"{md_prefix(indent)} [{filename}]({url})")
|
||||
return "\n".join(g_output)
|
||||
|
||||
|
||||
with open("DIRECTORY.md", "w") as out_file:
|
||||
out_file.write(build_directory_md(".") + "\n")
|
||||
|
||||
- name: Update DIRECTORY.md
|
||||
run: |
|
||||
cat DIRECTORY.md
|
||||
git config --global user.name github-actions
|
||||
git config --global user.email '${GITHUB_ACTOR}@users.noreply.github.com'
|
||||
git remote set-url origin https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/$GITHUB_REPOSITORY
|
||||
git add DIRECTORY.md
|
||||
git commit -am "updating DIRECTORY.md" || true
|
||||
git push --force origin HEAD:$GITHUB_REF || true
|
||||
34
.gitignore
vendored
Normal file
34
.gitignore
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
.DS_Store
|
||||
|
||||
# Prerequisites
|
||||
*.d
|
||||
|
||||
# Compiled Object files
|
||||
*.slo
|
||||
*.lo
|
||||
*.o
|
||||
*.obj
|
||||
|
||||
# Precompiled Headers
|
||||
*.gch
|
||||
*.pch
|
||||
|
||||
# Compiled Dynamic libraries
|
||||
*.so
|
||||
*.dylib
|
||||
*.dll
|
||||
|
||||
# Fortran module files
|
||||
*.mod
|
||||
*.smod
|
||||
|
||||
# Compiled Static libraries
|
||||
*.lai
|
||||
*.la
|
||||
*.a
|
||||
*.lib
|
||||
|
||||
# Executables
|
||||
*.exe
|
||||
*.out
|
||||
*.app
|
||||
67
.vscode/settings.json
vendored
Normal file
67
.vscode/settings.json
vendored
Normal file
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"files.associations": {
|
||||
"array": "cpp",
|
||||
"atomic": "cpp",
|
||||
"*.tcc": "cpp",
|
||||
"bitset": "cpp",
|
||||
"cctype": "cpp",
|
||||
"cfenv": "cpp",
|
||||
"chrono": "cpp",
|
||||
"cinttypes": "cpp",
|
||||
"clocale": "cpp",
|
||||
"cmath": "cpp",
|
||||
"codecvt": "cpp",
|
||||
"complex": "cpp",
|
||||
"condition_variable": "cpp",
|
||||
"csetjmp": "cpp",
|
||||
"csignal": "cpp",
|
||||
"cstdarg": "cpp",
|
||||
"cstddef": "cpp",
|
||||
"cstdint": "cpp",
|
||||
"cstdio": "cpp",
|
||||
"cstdlib": "cpp",
|
||||
"cstring": "cpp",
|
||||
"ctime": "cpp",
|
||||
"cuchar": "cpp",
|
||||
"cwchar": "cpp",
|
||||
"cwctype": "cpp",
|
||||
"deque": "cpp",
|
||||
"forward_list": "cpp",
|
||||
"list": "cpp",
|
||||
"unordered_map": "cpp",
|
||||
"unordered_set": "cpp",
|
||||
"vector": "cpp",
|
||||
"exception": "cpp",
|
||||
"fstream": "cpp",
|
||||
"functional": "cpp",
|
||||
"future": "cpp",
|
||||
"initializer_list": "cpp",
|
||||
"iomanip": "cpp",
|
||||
"iosfwd": "cpp",
|
||||
"iostream": "cpp",
|
||||
"istream": "cpp",
|
||||
"limits": "cpp",
|
||||
"memory": "cpp",
|
||||
"mutex": "cpp",
|
||||
"new": "cpp",
|
||||
"numeric": "cpp",
|
||||
"optional": "cpp",
|
||||
"ostream": "cpp",
|
||||
"ratio": "cpp",
|
||||
"scoped_allocator": "cpp",
|
||||
"shared_mutex": "cpp",
|
||||
"sstream": "cpp",
|
||||
"stdexcept": "cpp",
|
||||
"streambuf": "cpp",
|
||||
"string_view": "cpp",
|
||||
"system_error": "cpp",
|
||||
"thread": "cpp",
|
||||
"type_traits": "cpp",
|
||||
"tuple": "cpp",
|
||||
"typeindex": "cpp",
|
||||
"typeinfo": "cpp",
|
||||
"utility": "cpp",
|
||||
"valarray": "cpp",
|
||||
"algorithm": "cpp"
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
/*
|
||||
A Maze is given as N*N binary matrix of blocks where source block is the upper
|
||||
left most block i.e., maze[0][0] and destination block is lower rightmost
|
||||
block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination.
|
||||
The rat can move only in two directions: forward and down. In the maze matrix,
|
||||
0 means the block is dead end and 1 means the block can be used in the path
|
||||
from source to destination.
|
||||
*/
|
||||
#include <iostream>
|
||||
#define size 4
|
||||
|
||||
using namespace std;
|
||||
|
||||
int solveMaze(int currposrow,int currposcol,int maze[size][size],int soln[size][size])
|
||||
{
|
||||
if((currposrow==size-1) && (currposcol==size-1))
|
||||
{
|
||||
soln[currposrow][currposcol]=1;
|
||||
for(int i=0;i<size;++i)
|
||||
{
|
||||
for (int j=0;j<size;++j)
|
||||
{
|
||||
cout<<soln[i][j];
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
soln[currposrow][currposcol]=1;
|
||||
|
||||
// if there exist a solution by moving one step ahead in a collumn
|
||||
if((currposcol<size-1) && maze[currposrow][currposcol+1]==1 && solveMaze(currposrow,currposcol+1,maze,soln))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
// if there exists a solution by moving one step ahead in a row
|
||||
if((currposrow<size-1) && maze[currposrow+1][currposcol]==1 && solveMaze(currposrow+1,currposcol,maze,soln))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
// the backtracking part
|
||||
soln[currposrow][currposcol]=0;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int maze[size][size]={
|
||||
{1,0,1,0},
|
||||
{1,0,1,1},
|
||||
{1,0,0,1},
|
||||
{1,1,1,1}
|
||||
};
|
||||
|
||||
int soln[size][size];
|
||||
|
||||
for(int i=0;i<size;++i)
|
||||
{
|
||||
for (int j=0;j<size;++j)
|
||||
{
|
||||
soln[i][j]=0;
|
||||
}
|
||||
}
|
||||
|
||||
int currposrow=0;
|
||||
int currposcol=0;
|
||||
solveMaze(currposrow,currposcol,maze,soln);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,102 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
///N=9;
|
||||
int n=9;
|
||||
|
||||
|
||||
bool isPossible(int mat[][9],int i,int j,int no){
|
||||
///Row or col nahin hona chahiye
|
||||
for(int x=0;x<n;x++){
|
||||
if(mat[x][j]==no||mat[i][x]==no){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subgrid mein nahi hona chahiye
|
||||
int sx = (i/3)*3;
|
||||
int sy = (j/3)*3;
|
||||
|
||||
for(int x=sx;x<sx+3;x++){
|
||||
for(int y=sy;y<sy+3;y++){
|
||||
if(mat[x][y]==no){
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void printMat(int mat[][9]){
|
||||
|
||||
for(int i=0;i<n;i++){
|
||||
for(int j=0;j<n;j++){
|
||||
cout<<mat[i][j]<<" ";
|
||||
if((j+1)%3==0){
|
||||
cout<<'\t';
|
||||
}
|
||||
|
||||
}
|
||||
if((i+1)%3==0){
|
||||
cout<<endl;
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool solveSudoku(int mat[][9],int i,int j){
|
||||
///Base Case
|
||||
if(i==9){
|
||||
///Solve kr chuke hain for 9 rows already
|
||||
printMat(mat);
|
||||
return true;
|
||||
}
|
||||
|
||||
///Crossed the last Cell in the row
|
||||
if(j==9){
|
||||
return solveSudoku(mat,i+1,0);
|
||||
}
|
||||
|
||||
///Blue Cell - Skip
|
||||
if(mat[i][j]!=0){
|
||||
return solveSudoku(mat,i,j+1);
|
||||
}
|
||||
///White Cell
|
||||
///Try to place every possible no
|
||||
for(int no=1;no<=9;no++){
|
||||
if(isPossible(mat,i,j,no)){
|
||||
///Place the no - assuming solution aa jayega
|
||||
mat[i][j] = no;
|
||||
bool aageKiSolveHui = solveSudoku(mat,i,j+1);
|
||||
if(aageKiSolveHui){
|
||||
return true;
|
||||
}
|
||||
///Nahin solve hui
|
||||
///loop will place the next no.
|
||||
}
|
||||
}
|
||||
///Sare no try kr liey, kisi se bhi solve nahi hui
|
||||
mat[i][j] = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
int main(){
|
||||
|
||||
int mat[9][9] =
|
||||
{{5,3,0,0,7,0,0,0,0},
|
||||
{6,0,0,1,9,5,0,0,0},
|
||||
{0,9,8,0,0,0,0,6,0},
|
||||
{8,0,0,0,6,0,0,0,3},
|
||||
{4,0,0,8,0,3,0,0,1},
|
||||
{7,0,0,0,2,0,0,0,6},
|
||||
{0,6,0,0,0,0,2,8,0},
|
||||
{0,0,0,4,1,9,0,0,5},
|
||||
{0,0,0,0,8,0,0,7,9}};
|
||||
|
||||
printMat(mat);
|
||||
cout<<"Solution "<<endl;
|
||||
solveSudoku(mat,0,0);
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
98
CONTRIBUTION.md
Normal file
98
CONTRIBUTION.md
Normal file
@@ -0,0 +1,98 @@
|
||||
# CONTRIBUTION GUIDELINES
|
||||
|
||||
## Before contributing
|
||||
Welcome to [TheAlgorithms/C-Plus-Plus](https://github.com/TheAlgorithms/C-Plus-Plus)! Before submitting pull requests, please make sure that you have **read the whole guidelines**. If you have any doubts about this contribution guide, please open [an issue](https://github.com/TheAlgorithms/C-Plus-Plus/issues/new/choose) and clearly state your concerns.
|
||||
|
||||
## Contributing
|
||||
### Contributor
|
||||
We are very happy that you consider implementing algorithms and data structures for others! This repository is referred to and used by learners from around the globe. Being one of our contributors, you agree and confirm that:
|
||||
- You did your own work.
|
||||
- No plagiarism allowed. Any plagiarized work will not be merged.
|
||||
- Your work will be distributed under [MIT License](License) once your pull request has been merged.
|
||||
- You submitted work fulfils or mostly fulfils our styles and standards.
|
||||
|
||||
**New implementation** New implementation are welcome!
|
||||
**Improving comments** and **adding tests** to existing algorithms are much appreciated.
|
||||
|
||||
### Making Changes
|
||||
|
||||
#### Code
|
||||
- Please use the directory structure of the repository.
|
||||
- File extension for code should be *.h *.cpp.
|
||||
- Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compilation process.
|
||||
- Avoid using **struct** and instead use the **class** keyword.
|
||||
- You can suggest reasonable changes to existing algorithms.
|
||||
- Strictly use snake_case (underscore_separated) in filenames.
|
||||
- If you have added or modified code, please make sure the code compiles before submitting.
|
||||
- Our automated testing runs [__cpplint__](https://github.com/cpplint/cpplint) on all pull requests so please be sure that your code passes before submitting.
|
||||
- **Be consistent in use of these guidelines.**
|
||||
|
||||
#### New File Name guidelines
|
||||
- Use lowercase words with ``"_"`` as separator
|
||||
- For instance
|
||||
```
|
||||
MyNewCppClass.CPP is incorrect
|
||||
my_new_cpp_class.cpp is correct format
|
||||
```
|
||||
- It will be used to dynamically create a directory of files and implementation.
|
||||
- File name validation will run on docker to ensure the validity.
|
||||
|
||||
#### New Directory guidelines
|
||||
- We recommend adding files to existing directories as much as possible.
|
||||
- Use lowercase words with ``"_"`` as separator ( no spaces or ```"-"``` allowed )
|
||||
- For instance
|
||||
```
|
||||
SomeNew Fancy-Category is incorrect
|
||||
some_new_fancy_category is correct
|
||||
```
|
||||
- Filepaths will be used to dynamically create a directory of our algorithms.
|
||||
- Filepath validation will run on GitHub Actions to ensure compliance.
|
||||
|
||||
#### Commit Guidelines
|
||||
- It is recommended to keep your changes grouped logically within individual commits. Maintainers find it easier to understand changes that are logically spilt across multiple commits. Try to modify just one or two files in the same directory. Pull requests that span multiple directories are often rejected.
|
||||
```
|
||||
git add file_xyz.cpp
|
||||
git commit -m "your message"
|
||||
```
|
||||
Examples of commit messages with semantic prefixes:
|
||||
```
|
||||
fix: xyz algorithm bug
|
||||
feat: add xyx algorithm, class xyz
|
||||
test: add test for xyz algorithm
|
||||
docs: add comments and explanation to xyz algorithm
|
||||
```
|
||||
Common prefixes:
|
||||
- fix: A bug fix
|
||||
- feat: A new feature
|
||||
- docs: Documentation changes
|
||||
- test: Correct existing tests or add new ones
|
||||
|
||||
#### Documentation
|
||||
- Make sure you put useful comments in your code. Do not comment things that are obvious.
|
||||
- Please avoid creating new directories if at all possible. Try to fit your work into the existing directory structure. If you want to create a new directory, then please check if a similar category has been recently suggested or created by other pull requests.
|
||||
- If you have modified/added documentation, please ensure that your language is concise and contains no grammar errors.
|
||||
- Do not update README.md along with other changes, first create an issue and then link to that issue in your pull request to suggest specific changes required to README.md
|
||||
|
||||
#### Test
|
||||
- Make sure to add examples and test cases in your main() function.
|
||||
- If you find any algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes.
|
||||
|
||||
### Pull Requests
|
||||
- Checkout our [pull request template](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/.github/pull_request_template.md)
|
||||
|
||||
#### cpplint
|
||||
To see if [__cpplint__](https://github.com/cpplint/cpplint) is already installed, do:
|
||||
* `cpplint --version` # currently returns "cpplint 1.4.4"
|
||||
If cpplint is ___not___ installed then do:
|
||||
* `python3 -m pip install cpplint` # If that does not work then try...
|
||||
* `py -m pip install cpplint` # If that does not work then try...
|
||||
* `pip install cpplint`
|
||||
Once cpplint is installed, test your file(s) with:
|
||||
* `cpplint --filter=-legal my_file.cpp my_other_file.cpp` # Fix any issues and try again.
|
||||
|
||||
The [__clang-format__](https://clang.llvm.org/docs/ClangFormat.html) tool can fix whitespace related _cpplint_ issues.
|
||||
* On Macs only: `brew install clang-format` # Only needs to be installed once.
|
||||
* All platforms: `clang-format -i -style="{IndentWidth: 4}" my_file.cpp`
|
||||
|
||||
Most importantly,
|
||||
- Happy coding!
|
||||
@@ -1,53 +0,0 @@
|
||||
#include<iostream.h>
|
||||
#include<conio.h>
|
||||
#include<math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i,3)-(4*i)-9); // original equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a,b,x,z;
|
||||
clrscr();
|
||||
for(int i=0;i<100;i++)
|
||||
{
|
||||
z=eq(i);
|
||||
if(z>=0)
|
||||
{
|
||||
b=i;
|
||||
a=--i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout<<"\nFirst initial: "<<a;
|
||||
cout<<"\nSecond initial: "<<b;
|
||||
for(i=0;i<100;i++)
|
||||
{
|
||||
x=(a+b)/2;
|
||||
z=eq(x);
|
||||
cout<<"\n\nz: "<<z<<"\t["<<a<<" , "<<b<<" | Bisect: "<<x<<"]";
|
||||
|
||||
if(z < 0)
|
||||
{
|
||||
a=x;
|
||||
}
|
||||
else
|
||||
{
|
||||
b=x;
|
||||
}
|
||||
|
||||
if(z > 0 && z<0.0009) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout<<"\n\nRoot: "<<x;
|
||||
getch();
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
#include<bits/stdc++.h>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int mat_size,i,j,step;
|
||||
|
||||
cout<<"Matrix size: ";
|
||||
cin>>mat_size;
|
||||
|
||||
double mat[mat_size+1][mat_size+1], x[mat_size][mat_size+1];
|
||||
|
||||
cout<<endl<<"Enter value of the matrix: "<<endl;
|
||||
for(i=0;i<mat_size;i++)
|
||||
{
|
||||
for(j=0;j<=mat_size;j++)
|
||||
{
|
||||
cin>>mat[i][j]; //Enter (mat_size*mat_size) value of the matrix.
|
||||
}
|
||||
}
|
||||
|
||||
for(step=0;step<mat_size-1;step++){
|
||||
for(i=step;i<mat_size-1;i++)
|
||||
{
|
||||
double a = (mat[i+1][step]/mat[step][step]);
|
||||
|
||||
for(j=step;j<=mat_size;j++)
|
||||
mat[i+1][j] = mat[i+1][j] - (a * mat[step][j]);
|
||||
}
|
||||
}
|
||||
|
||||
cout<<endl<<"Matrix using Gaussian Elimination method: "<<endl;
|
||||
for(i=0;i<mat_size;i++)
|
||||
{
|
||||
for(j=0;j<=mat_size;j++)
|
||||
{
|
||||
x[i][j] = mat[i][j];
|
||||
cout<<mat[i][j]<<" ";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
cout<<endl<<"Value of the Gaussian Elimination method: "<<endl;
|
||||
for(i=mat_size-1;i>=0;i--)
|
||||
{
|
||||
double sum = 0;
|
||||
for(j=mat_size-1;j>i;j--)
|
||||
{
|
||||
x[i][j] = x[j][j] * x[i][j];
|
||||
sum = x[i][j] + sum;
|
||||
}
|
||||
if(x[i][i]==0)
|
||||
x[i][i] = 0;
|
||||
else
|
||||
x[i][i] = (x[i][mat_size] - sum)/(x[i][i]);
|
||||
|
||||
cout<<"x"<<i<<"= "<<x[i][i]<<endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
#include<iostream.h>
|
||||
#include<conio.h>
|
||||
#include<math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i,3)-(4*i)-9); // original equation
|
||||
}
|
||||
float eq_der(float i)
|
||||
{
|
||||
return ((3*pow(i,2))-4); // derivative of equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a,b,z,c,m,n;
|
||||
clrscr();
|
||||
for(int i=0;i<100;i++)
|
||||
{
|
||||
z=eq(i);
|
||||
if(z>=0)
|
||||
{
|
||||
b=i;
|
||||
a=--i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout<<"\nFirst initial: "<<a;
|
||||
cout<<"\nSecond initial: "<<b;
|
||||
c=(a+b)/2;
|
||||
|
||||
for(i=0;i<100;i++)
|
||||
{
|
||||
float h;
|
||||
m=eq(c);
|
||||
n=eq_der(c);
|
||||
|
||||
z=c-(m/n);
|
||||
c=z;
|
||||
|
||||
if(m > 0 && m<0.009) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout<<"\n\nRoot: "<<z;
|
||||
getch();
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#include<iostream.h>
|
||||
#include<conio.h>
|
||||
#include<math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i,3)-(4*i)-9); // original equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a,b,z,c,m,n;
|
||||
clrscr();
|
||||
for(int i=0;i<100;i++)
|
||||
{
|
||||
z=eq(i);
|
||||
if(z>=0)
|
||||
{
|
||||
b=i;
|
||||
a=--i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout<<"\nFirst initial: "<<a;
|
||||
cout<<"\nSecond initial: "<<b;
|
||||
for(i=0;i<100;i++)
|
||||
{
|
||||
float h,d;
|
||||
m=eq(a);
|
||||
n=eq(b);
|
||||
|
||||
c=((a*n)-(b*m))/(n-m);
|
||||
a=b;
|
||||
b=c;
|
||||
|
||||
z=eq(c);
|
||||
if(z > 0 && z<0.09) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout<<"\n\nRoot: "<<c;
|
||||
getch();
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#include<iostream.h>
|
||||
#include<conio.h>
|
||||
#include<math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i,3)-(4*i)-9); // origial equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a,b,z,c,m,n;
|
||||
clrscr();
|
||||
for(int i=0;i<100;i++)
|
||||
{
|
||||
z=eq(i);
|
||||
if(z>=0)
|
||||
{
|
||||
b=i;
|
||||
a=--i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout<<"\nFirst initial: "<<a;
|
||||
cout<<"\nSecond initial: "<<b;
|
||||
for(i=0;i<100;i++)
|
||||
{
|
||||
|
||||
float h,d;
|
||||
m=eq(a);
|
||||
n=eq(b);
|
||||
|
||||
c=((a*n)-(b*m))/(n-m);
|
||||
a=c;
|
||||
|
||||
z=eq(c);
|
||||
if(z > 0 && z<0.09) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout<<"\n\nRoot: "<<c;
|
||||
getch();
|
||||
}
|
||||
@@ -1,37 +0,0 @@
|
||||
#include<conio.h>
|
||||
#include<iostream.h>
|
||||
#include<math.h>
|
||||
float eq(float y)
|
||||
{
|
||||
return((3*y)-(cos(y))-2);
|
||||
}
|
||||
float eqd(float y)
|
||||
{
|
||||
return((0.5)*((cos(y))+2));
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float y,x1,x2,x3,sum,s,a,f1,f2,gd;
|
||||
int i,n;
|
||||
|
||||
clrscr();
|
||||
for(i=0;i<10;i++)
|
||||
{
|
||||
sum=eq(y);
|
||||
cout<<"value of equation at "<<i<<" "<<sum<<"\n";
|
||||
y++;
|
||||
}
|
||||
cout<<"enter the x1->";
|
||||
cin>>x1;
|
||||
cout<<"enter the no iteration to perform->\n";
|
||||
cin>>n;
|
||||
|
||||
for(i=0;i<=n;i++)
|
||||
{
|
||||
x2=eqd(x1);
|
||||
cout<<"\nenter the x2->"<<x2;
|
||||
x1=x2;
|
||||
}
|
||||
getch();
|
||||
}
|
||||
186
DIRECTORY.md
Normal file
186
DIRECTORY.md
Normal file
@@ -0,0 +1,186 @@
|
||||
|
||||
## Backtracking
|
||||
* [Graph Coloring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/graph_coloring.cpp)
|
||||
* [Knight Tour](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/knight_tour.cpp)
|
||||
* [Minimax](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/minimax.cpp)
|
||||
* [N Queens](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/n_queens.cpp)
|
||||
* [Nqueen Print All Solutions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/nqueen_print_all_solutions.cpp)
|
||||
* [Rat Maze](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/rat_maze.cpp)
|
||||
* [Sudoku Solve](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/sudoku_solve.cpp)
|
||||
|
||||
## Computer Oriented Statistical Methods
|
||||
* [Bisection Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Bisection_method.CPP)
|
||||
* [False-Position](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/false-position.cpp)
|
||||
* [Gaussian Elimination](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Gaussian_elimination.cpp)
|
||||
* [Newton Raphson](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Newton_Raphson.CPP)
|
||||
* [Secant Method](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/Secant_method.CPP)
|
||||
* [Successive Approximation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/computer_oriented_statistical_methods/successive_approximation.CPP)
|
||||
|
||||
## Data Structure
|
||||
* [Avltree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/AVLtree.cpp)
|
||||
* [Binary Search Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binary%20Search%20Tree.cpp)
|
||||
* [Binaryheap](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Binaryheap.cpp)
|
||||
* [Circular Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/circular_Queue_using_Linked_List.cpp)
|
||||
* Cll
|
||||
* [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.cpp)
|
||||
* [Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/cll.h)
|
||||
* [Main Cll](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/cll/main_cll.cpp)
|
||||
* [Disjoint Set](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/disjoint_set.cpp)
|
||||
* [Doubly Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Doubly%20Linked%20List.cpp)
|
||||
* [Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linked_list.cpp)
|
||||
* [Linkedlist Implentation Usingarray](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/linkedList_implentation_usingArray.cpp)
|
||||
* [List Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/List%20Array.cpp)
|
||||
* [Morrisinorder](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/MorrisInorder.cpp)
|
||||
* [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Array.cpp)
|
||||
* [Queue Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Queue%20Using%20Linked%20List.cpp)
|
||||
* Queue
|
||||
* [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.cpp)
|
||||
* [Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/queue.h)
|
||||
* [Test Queue](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue/test_queue.cpp)
|
||||
* [Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_array.cpp)
|
||||
* [Queue Using Linkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/queue_using_linkedlist.cpp)
|
||||
* [Stack Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Array.cpp)
|
||||
* [Stack Using Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Stack%20Using%20Linked%20List.cpp)
|
||||
* Stk
|
||||
* [Main](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/main.cpp)
|
||||
* [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.cpp)
|
||||
* [Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/stack.h)
|
||||
* [Test Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/stk/test_stack.cpp)
|
||||
* [Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/Tree.cpp)
|
||||
* [Trie Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/data_structure/trie_tree.cpp)
|
||||
|
||||
## Dynamic Programming
|
||||
* [0-1 Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/0-1%20Knapsack.cpp)
|
||||
* [Armstrong Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/armstrong_number.cpp)
|
||||
* [Bellman-Ford](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Bellman-Ford.cpp)
|
||||
* [Catalan-Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Catalan-Numbers.cpp)
|
||||
* [Coin-Change](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Coin-Change.cpp)
|
||||
* [Cut Rod](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Cut%20Rod.cpp)
|
||||
* [Edit Distance](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Edit%20Distance.cpp)
|
||||
* [Egg-Dropping-Puzzle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Egg-Dropping-Puzzle.cpp)
|
||||
* [Fibonacci Bottom Up](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Bottom_Up.cpp)
|
||||
* [Fibonacci Top Down](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Fibonacci_Top_Down.cpp)
|
||||
* [Floyd-Warshall](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Floyd-Warshall.cpp)
|
||||
* [Kadane](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/kadane.cpp)
|
||||
* [Longest Common Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Common%20Subsequence.cpp)
|
||||
* [Longest Increasing Subsequence (Nlogn)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence%20(nlogn).cpp)
|
||||
* [Longest Increasing Subsequence](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Longest%20Increasing%20Subsequence.cpp)
|
||||
* [Longest Common String](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/longest_common_string.cpp)
|
||||
* [Matrix-Chain-Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/Matrix-Chain-Multiplication.cpp)
|
||||
* [Searching Of Element In Dynamic Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/searching_of_element_in_dynamic_array.cpp)
|
||||
* [Tree Height](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/dynamic_programming/tree_height.cpp)
|
||||
|
||||
## Graph
|
||||
* [Bfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/BFS.cpp)
|
||||
* [Dfs](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS.cpp)
|
||||
* [Dfs With Stack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/DFS_with_stack.cc)
|
||||
* [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Dijkstra.cpp)
|
||||
* [Kosaraju](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/kosaraju.cpp)
|
||||
* [Kruskal](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Kruskal.cpp)
|
||||
* [Lca](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/lca.cpp)
|
||||
* [Topological-Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/graph/Topological-Sort.cpp)
|
||||
|
||||
## Greedy Algorithms
|
||||
* [Dijkstra](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Dijkstra.cpp)
|
||||
* [Huffman](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/huffman.cpp)
|
||||
* [Knapsack](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Knapsack.cpp)
|
||||
* [Kruskals Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Kruskals%20Minimum%20Spanning%20Tree.cpp)
|
||||
* [Prims Minimum Spanning Tree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/greedy_algorithms/Prims%20Minimum%20Spanning%20Tree.cpp)
|
||||
|
||||
## Hashing
|
||||
* [Chaining](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/Chaining.cpp)
|
||||
* [Double Hash Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/double_hash_hash_table.cpp)
|
||||
* [Linear Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/linear_probing_hash_table.cpp)
|
||||
* [Quadratic Probing Hash Table](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/hashing/quadratic_probing_hash_table.cpp)
|
||||
|
||||
## Math
|
||||
* [Binary Exponent](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/binary_exponent.cpp)
|
||||
* [Eulers Totient Function](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/eulers_totient_function.cpp)
|
||||
* [Factorial](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/factorial.cpp)
|
||||
* [Fast Power](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/fast_power.cpp)
|
||||
* [Greatest Common Divisor](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor.cpp)
|
||||
* [Greatest Common Divisor Euclidean](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/greatest_common_divisor_euclidean.cpp)
|
||||
* [Number Of Positive Divisors](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/number_of_positive_divisors.cpp)
|
||||
* [Power For Huge Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/power_for_huge_numbers.cpp)
|
||||
* [Prime Factorization](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_factorization.cpp)
|
||||
* [Prime Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/prime_numbers.cpp)
|
||||
* [Primes Up To 10^8](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/primes_up_to_10^8.cpp)
|
||||
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/math/sieve_of_eratosthenes.cpp)
|
||||
|
||||
## Operations On Datastructures
|
||||
* [Array Left Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Left%20Rotation.cpp)
|
||||
* [Array Right Rotation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Array%20Right%20Rotation.cpp)
|
||||
* [Circular Linked List](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Linked%20List.cpp)
|
||||
* [Circular Queue Using Array](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Circular%20Queue%20Using%20Array.cpp)
|
||||
* [Intersection Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Intersection_of_2_arrays.cpp)
|
||||
* [Reverse A Linked List Using Recusion](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Reverse%20a%20Linked%20List%20using%20Recusion.cpp)
|
||||
* [Selectionsortlinkedlist](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/selectionSortLinkedList.cpp)
|
||||
* [Union Of 2 Arrays](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/operations_on_datastructures/Union_of_2_arrays.cpp)
|
||||
|
||||
## Others
|
||||
* [Buzz Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Buzz_number.cpp)
|
||||
* [Decimal To Binary](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Binary.cpp)
|
||||
* [Decimal To Hexadecimal ](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20To%20Hexadecimal%20.cpp)
|
||||
* [Decimal To Roman Numeral](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Decimal%20to%20Roman%20Numeral.cpp)
|
||||
* [Fast Interger Input](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fast_interger_input.cpp)
|
||||
* [Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/fibonacci.cpp)
|
||||
* [Gcd Of N Numbers](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/GCD_of_n_numbers.cpp)
|
||||
* [Happy Number](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/happy_number.cpp)
|
||||
* [Matrix Exponentiation](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/matrix_exponentiation.cpp)
|
||||
* [Measure Time Elapsed](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/measure_time_elapsed.cpp)
|
||||
* [Palindromeofnumber](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Palindromeofnumber.cpp)
|
||||
* [Paranthesis Matching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Paranthesis%20Matching.cpp)
|
||||
* [Pascal Triangle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/pascal_triangle.cpp)
|
||||
* [Primality Test](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Primality%20Test.cpp)
|
||||
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/sieve_of_Eratosthenes.cpp)
|
||||
* [Smallest-Circle](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/smallest-circle.cpp)
|
||||
* [Sparse Matrix](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Sparse%20matrix.cpp)
|
||||
* [Spiral Print](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/spiral_print.cpp)
|
||||
* [Stairs Pattern](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/stairs_pattern.cpp)
|
||||
* [Strassen Matrix Multiplication](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Strassen%20Matrix%20Multiplication.cpp)
|
||||
* [String Fibonacci](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/String%20Fibonacci.cpp)
|
||||
* [Tower Of Hanoi](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/Tower%20of%20Hanoi.cpp)
|
||||
* [Vector Important Functions](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/others/vector_important_functions.cpp)
|
||||
|
||||
## Range Queries
|
||||
* [Bit](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/bit.cpp)
|
||||
* [Fenwicktree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/FenwickTree.cpp)
|
||||
* [Mo](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/MO.cpp)
|
||||
* [Segtree](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/range_queries/segTree.cpp)
|
||||
|
||||
## Search
|
||||
* [Binary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Binary%20Search.cpp)
|
||||
* [Exponential Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/exponential_search.cpp)
|
||||
* [Hash Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/hash_search.cpp)
|
||||
* [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Interpolation%20Search.cpp)
|
||||
* [Interpolation Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/interpolation_search.cpp)
|
||||
* [Linear Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/Linear%20Search.cpp)
|
||||
* [Median Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/median_search.cpp)
|
||||
* [Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/searching.cpp)
|
||||
* [Ternary Search](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/search/ternary_search.cpp)
|
||||
|
||||
## Sorting
|
||||
* [Beadsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BeadSort.cpp)
|
||||
* [Bitonicsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/BitonicSort.cpp)
|
||||
* [Bubble Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Bubble%20Sort.cpp)
|
||||
* [Bucketsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/bucketSort.cpp)
|
||||
* [Cocktailselectionsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CocktailSelectionSort.cpp)
|
||||
* [Combsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/combsort.cpp)
|
||||
* [Counting Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Counting_Sort.cpp)
|
||||
* [Countingsortstring](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/CountingSortString.cpp)
|
||||
* [Heap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/heap_sort.cpp)
|
||||
* [Insertion Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Insertion%20Sort.cpp)
|
||||
* [Library Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/library_sort.cpp)
|
||||
* [Merge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Merge%20Sort.cpp)
|
||||
* [Numericstringsort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/NumericStringSort.cpp)
|
||||
* [Oddeven Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/OddEven%20Sort.cpp)
|
||||
* [Quick Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Quick%20Sort.cpp)
|
||||
* [Radix Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Radix%20Sort.cpp)
|
||||
* [Selection Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Selection%20Sort.cpp)
|
||||
* [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Shell%20Sort.cpp)
|
||||
* [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Slow%20Sort.cpp)
|
||||
* [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/Tim%20Sort.cpp)
|
||||
|
||||
## Strings
|
||||
* [Brute Force String Searching](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/brute_force_string_searching.cpp)
|
||||
* [Knuth Morris Pratt](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/strings/knuth_morris_pratt.cpp)
|
||||
@@ -1,232 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
struct queue
|
||||
{
|
||||
node *t[100];
|
||||
int front;
|
||||
int rear;
|
||||
};
|
||||
|
||||
queue q;
|
||||
|
||||
|
||||
void enqueue(node *n)
|
||||
{
|
||||
q.t[q.rear++]=n;
|
||||
}
|
||||
|
||||
node * dequeue()
|
||||
{
|
||||
return (q.t[q.front++]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void Insert(node *n, int x)
|
||||
{
|
||||
if (x<n->val)
|
||||
{
|
||||
if (n->left==NULL)
|
||||
{
|
||||
node *temp=new node;
|
||||
temp->val=x;
|
||||
temp->left=NULL;
|
||||
temp->right=NULL;
|
||||
n->left=temp;
|
||||
}
|
||||
else
|
||||
{
|
||||
Insert(n->left, x);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (n->right==NULL)
|
||||
{
|
||||
node *temp=new node;
|
||||
temp->val=x;
|
||||
temp->left=NULL;
|
||||
temp->right=NULL;
|
||||
n->left=temp;
|
||||
}
|
||||
else
|
||||
{
|
||||
Insert(n->right, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int findMaxInLeftST(node *n)
|
||||
{
|
||||
while(n->right!=NULL)
|
||||
{
|
||||
n=n->right;
|
||||
}
|
||||
return n->val;
|
||||
}
|
||||
|
||||
void Remove(node *p, node *n, int x)
|
||||
{
|
||||
if (n->val==x)
|
||||
{
|
||||
if (n->right==NULL && n->left==NULL)
|
||||
{
|
||||
if (x<p->val)
|
||||
{
|
||||
p->right=NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left=NULL;
|
||||
}
|
||||
}
|
||||
else if (n->right==NULL)
|
||||
{
|
||||
if (x<p->val)
|
||||
{
|
||||
p->right=n->left;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left=n->left;
|
||||
}
|
||||
}
|
||||
else if (n->left==NULL)
|
||||
{
|
||||
if (x<p->val)
|
||||
{
|
||||
p->right=n->right;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left=n->right;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int y=findMaxInLeftST(n->left);
|
||||
n->val=y;
|
||||
Remove(n, n->right, y);
|
||||
}
|
||||
}
|
||||
else if (x<n->val)
|
||||
{
|
||||
Remove(n, n->left, x);
|
||||
}
|
||||
else
|
||||
{
|
||||
Remove(n, n->right, x);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void BFT(node *n)
|
||||
{
|
||||
if(n!=NULL)
|
||||
{
|
||||
cout<<n->val<<" ";
|
||||
enqueue(n->left);
|
||||
enqueue(n->right);
|
||||
BFT(dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
void Pre(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
cout<<n->val<<" ";
|
||||
Pre(n->left);
|
||||
Pre(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void In(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
In(n->left);
|
||||
cout<<n->val<<" ";
|
||||
In(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Post(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
Post(n->left);
|
||||
Post(n->right);
|
||||
cout<<n->val<<" ";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
q.front=0;
|
||||
q.rear=0;
|
||||
int value;
|
||||
int ch;
|
||||
node *root=new node;
|
||||
cout<<"\nEnter the value of root node :";
|
||||
cin>>value;
|
||||
root->val=value;
|
||||
root->left=NULL;
|
||||
root->right=NULL;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Insert";
|
||||
cout<<"\n2. Delete";
|
||||
cout<<"\n3. Breadth First";
|
||||
cout<<"\n4. Preorder Depth First";
|
||||
cout<<"\n5. Inorder Depth First";
|
||||
cout<<"\n6. Postorder Depth First";
|
||||
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
int x;
|
||||
switch(ch)
|
||||
{
|
||||
case 1:
|
||||
cout<<"\nEnter the value to be Inserted : ";
|
||||
cin>>x;
|
||||
Insert(root, x);
|
||||
break;
|
||||
case 2:
|
||||
cout<<"\nEnter the value to be Deleted : ";
|
||||
cin>>x;
|
||||
Remove(root, root, x);
|
||||
break;
|
||||
case 3:
|
||||
BFT(root);
|
||||
break;
|
||||
case 4:
|
||||
Pre(root);
|
||||
break;
|
||||
case 5:
|
||||
In(root);
|
||||
break;
|
||||
case 6:
|
||||
Post(root);
|
||||
break;
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
}
|
||||
@@ -1,159 +0,0 @@
|
||||
// A C++ program to demonstrate common Binary Heap Operations
|
||||
#include<iostream>
|
||||
#include<climits>
|
||||
using namespace std;
|
||||
|
||||
// Prototype of a utility function to swap two integers
|
||||
void swap(int *x, int *y);
|
||||
|
||||
// A class for Min Heap
|
||||
class MinHeap
|
||||
{
|
||||
int *harr; // pointer to array of elements in heap
|
||||
int capacity; // maximum possible size of min heap
|
||||
int heap_size; // Current number of elements in min heap
|
||||
public:
|
||||
// Constructor
|
||||
MinHeap(int capacity);
|
||||
|
||||
// to heapify a subtree with the root at given index
|
||||
void MinHeapify(int );
|
||||
|
||||
int parent(int i) { return (i-1)/2; }
|
||||
|
||||
// to get index of left child of node at index i
|
||||
int left(int i) { return (2*i + 1); }
|
||||
|
||||
// to get index of right child of node at index i
|
||||
int right(int i) { return (2*i + 2); }
|
||||
|
||||
// to extract the root which is the minimum element
|
||||
int extractMin();
|
||||
|
||||
// Decreases key value of key at index i to new_val
|
||||
void decreaseKey(int i, int new_val);
|
||||
|
||||
// Returns the minimum key (key at root) from min heap
|
||||
int getMin() { return harr[0]; }
|
||||
|
||||
// Deletes a key stored at index i
|
||||
void deleteKey(int i);
|
||||
|
||||
// Inserts a new key 'k'
|
||||
void insertKey(int k);
|
||||
};
|
||||
|
||||
// Constructor: Builds a heap from a given array a[] of given size
|
||||
MinHeap::MinHeap(int cap)
|
||||
{
|
||||
heap_size = 0;
|
||||
capacity = cap;
|
||||
harr = new int[cap];
|
||||
}
|
||||
|
||||
// Inserts a new key 'k'
|
||||
void MinHeap::insertKey(int k)
|
||||
{
|
||||
if (heap_size == capacity)
|
||||
{
|
||||
cout << "\nOverflow: Could not insertKey\n";
|
||||
return;
|
||||
}
|
||||
|
||||
// First insert the new key at the end
|
||||
heap_size++;
|
||||
int i = heap_size - 1;
|
||||
harr[i] = k;
|
||||
|
||||
// Fix the min heap property if it is violated
|
||||
while (i != 0 && harr[parent(i)] > harr[i])
|
||||
{
|
||||
swap(&harr[i], &harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Decreases value of key at index 'i' to new_val. It is assumed that
|
||||
// new_val is smaller than harr[i].
|
||||
void MinHeap::decreaseKey(int i, int new_val)
|
||||
{
|
||||
harr[i] = new_val;
|
||||
while (i != 0 && harr[parent(i)] > harr[i])
|
||||
{
|
||||
swap(&harr[i], &harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Method to remove minimum element (or root) from min heap
|
||||
int MinHeap::extractMin()
|
||||
{
|
||||
if (heap_size <= 0)
|
||||
return INT_MAX;
|
||||
if (heap_size == 1)
|
||||
{
|
||||
heap_size--;
|
||||
return harr[0];
|
||||
}
|
||||
|
||||
// Store the minimum value, and remove it from heap
|
||||
int root = harr[0];
|
||||
harr[0] = harr[heap_size-1];
|
||||
heap_size--;
|
||||
MinHeapify(0);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
|
||||
// This function deletes key at index i. It first reduced value to minus
|
||||
// infinite, then calls extractMin()
|
||||
void MinHeap::deleteKey(int i)
|
||||
{
|
||||
decreaseKey(i, INT_MIN);
|
||||
extractMin();
|
||||
}
|
||||
|
||||
// A recursive method to heapify a subtree with the root at given index
|
||||
// This method assumes that the subtrees are already heapified
|
||||
void MinHeap::MinHeapify(int i)
|
||||
{
|
||||
int l = left(i);
|
||||
int r = right(i);
|
||||
int smallest = i;
|
||||
if (l < heap_size && harr[l] < harr[i])
|
||||
smallest = l;
|
||||
if (r < heap_size && harr[r] < harr[smallest])
|
||||
smallest = r;
|
||||
if (smallest != i)
|
||||
{
|
||||
swap(&harr[i], &harr[smallest]);
|
||||
MinHeapify(smallest);
|
||||
}
|
||||
}
|
||||
|
||||
// A utility function to swap two elements
|
||||
void swap(int *x, int *y)
|
||||
{
|
||||
int temp = *x;
|
||||
*x = *y;
|
||||
*y = temp;
|
||||
}
|
||||
|
||||
// Driver program to test above functions
|
||||
int main()
|
||||
{
|
||||
MinHeap h(11);
|
||||
h.insertKey(3);
|
||||
h.insertKey(2);
|
||||
h.deleteKey(1);
|
||||
h.insertKey(15);
|
||||
h.insertKey(5);
|
||||
h.insertKey(4);
|
||||
h.insertKey(45);
|
||||
cout << h.extractMin() << " ";
|
||||
cout << h.getMin() << " ";
|
||||
h.decreaseKey(2, 1);
|
||||
cout << h.getMin();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *prev;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *start;
|
||||
|
||||
void insert(int x)
|
||||
{
|
||||
node *t=start;
|
||||
if (start!=NULL)
|
||||
{
|
||||
while(t->next!=NULL)
|
||||
{
|
||||
t=t->next;
|
||||
}
|
||||
node *n= new node;
|
||||
t->next=n;
|
||||
n->prev=t;
|
||||
n->val=x;
|
||||
n->next=NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
node *n= new node;
|
||||
n->val=x;
|
||||
n->prev=NULL;
|
||||
n->next=NULL;
|
||||
start=n;
|
||||
}
|
||||
}
|
||||
|
||||
void remove(int x)
|
||||
{
|
||||
node *t=start;
|
||||
while(t->val!=x)
|
||||
{
|
||||
t=t->next;
|
||||
}
|
||||
t->prev->next=t->next;
|
||||
t->next->prev=t->prev;
|
||||
delete t;
|
||||
}
|
||||
|
||||
void search(int x)
|
||||
{
|
||||
node *t= start;
|
||||
int found =0;
|
||||
while(t!=NULL)
|
||||
{
|
||||
if(t->val==x)
|
||||
{
|
||||
cout<<"\nFound";
|
||||
found=1;
|
||||
break;
|
||||
}
|
||||
t=t->next;
|
||||
}
|
||||
if(found==0)
|
||||
{
|
||||
cout<<"\nNot Found";
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
node *t=start;
|
||||
while(t!=NULL)
|
||||
{
|
||||
cout<<t->val<<"\t";
|
||||
t=t->next;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void reverseShow()
|
||||
{
|
||||
node *t=start;
|
||||
while(t->next!=NULL)
|
||||
{
|
||||
t=t->next;
|
||||
}
|
||||
while(t!=NULL)
|
||||
{
|
||||
cout<<t->val<<"\t";
|
||||
t=t->prev;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int choice, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Insert";
|
||||
cout<<"\n2. Delete";
|
||||
cout<<"\n3. Search";
|
||||
cout<<"\n4. Forward print";
|
||||
cout<<"\n5. Reverse print";
|
||||
cout<<"\n\nEnter you choice : ";
|
||||
cin>>choice;
|
||||
switch (choice)
|
||||
{
|
||||
case 1 : cout<<"\nEnter the element to be inserted : ";
|
||||
cin>>x;;
|
||||
insert(x); break;
|
||||
case 2 : cout<<"\nEnter the element to be removed : ";
|
||||
cin>>x;
|
||||
remove(x); break;
|
||||
case 3 : cout<<"\nEnter the element to be searched : ";
|
||||
cin>>x;
|
||||
search(x); break;
|
||||
case 4 : show(); break;
|
||||
case 5 : reverseShow(); break;
|
||||
}
|
||||
}
|
||||
while(choice!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,125 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *start;
|
||||
|
||||
void insert(int x)
|
||||
{
|
||||
node *t=start;
|
||||
if (start!=NULL)
|
||||
{
|
||||
while(t->next!=NULL)
|
||||
{
|
||||
t=t->next;
|
||||
}
|
||||
node *n= new node;
|
||||
t->next=n;
|
||||
n->val=x;
|
||||
n->next=NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
node *n= new node;
|
||||
n->val=x;
|
||||
n->next=NULL;
|
||||
start=n;
|
||||
}
|
||||
}
|
||||
|
||||
void remove(int x){
|
||||
|
||||
if( start == NULL ){
|
||||
cout<<"\nLinked List is empty\n";
|
||||
return ;
|
||||
}
|
||||
else if( start->val == x ){
|
||||
node *temp = start;
|
||||
start = start->next;
|
||||
delete temp;
|
||||
return ;
|
||||
}
|
||||
|
||||
node *temp = start, *parent = start;
|
||||
|
||||
while( temp != NULL && temp->val != x ){
|
||||
parent = temp;
|
||||
temp = temp->next;
|
||||
}
|
||||
|
||||
if( temp == NULL ){
|
||||
cout <<endl <<x <<" not found in list\n";
|
||||
return ;
|
||||
}
|
||||
|
||||
parent->next = temp->next;
|
||||
delete temp;
|
||||
}
|
||||
|
||||
void search(int x)
|
||||
{
|
||||
node *t= start;
|
||||
int found =0;
|
||||
while(t!=NULL)
|
||||
{
|
||||
if(t->val==x)
|
||||
{
|
||||
cout<<"\nFound";
|
||||
found=1;
|
||||
break;
|
||||
}
|
||||
t=t->next;
|
||||
}
|
||||
if(found==0)
|
||||
{
|
||||
cout<<"\nNot Found";
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
node *t=start;
|
||||
while(t!=NULL)
|
||||
{
|
||||
cout<<t->val<<"\t";
|
||||
t=t->next;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int choice, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Insert";
|
||||
cout<<"\n2. Delete";
|
||||
cout<<"\n3. Search";
|
||||
cout<<"\n4. Print";
|
||||
cout<<"\n0. Exit";
|
||||
cout<<"\n\nEnter you choice : ";
|
||||
cin>>choice;
|
||||
switch (choice)
|
||||
{
|
||||
case 1 : cout<<"\nEnter the element to be inserted : ";
|
||||
cin>>x;;
|
||||
insert(x); break;
|
||||
case 2 : cout<<"\nEnter the element to be removed : ";
|
||||
cin>>x;
|
||||
remove(x); break;
|
||||
case 3 : cout<<"\nEnter the element to be searched : ";
|
||||
cin>>x;
|
||||
search(x); break;
|
||||
case 4 : show();
|
||||
cout<<"\n"; break;
|
||||
}
|
||||
}
|
||||
while(choice!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,185 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct list
|
||||
{
|
||||
int data[50];
|
||||
int top=0;
|
||||
bool isSorted=false;
|
||||
|
||||
int BinarySearch(int *array, int first, int last, int x)
|
||||
{
|
||||
if(last<first)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
int mid=(first+last)/2;
|
||||
if(array[mid]==x)
|
||||
return mid;
|
||||
else if(x<array[mid])
|
||||
return (BinarySearch(array, first, mid-1, x));
|
||||
else if(x>array[mid])
|
||||
return (BinarySearch(array, mid+1, last, x));
|
||||
}
|
||||
|
||||
int LinarSearch(int *array, int x)
|
||||
{
|
||||
for (int i = 0; i < top; i++)
|
||||
{
|
||||
if (array[i]==x)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int Search(int x)
|
||||
{
|
||||
int pos=-1;
|
||||
|
||||
if (isSorted)
|
||||
{
|
||||
pos=BinarySearch(data, 0, top-1, x);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
pos=LinarSearch(data, x);
|
||||
}
|
||||
|
||||
if (pos!=-1)
|
||||
{
|
||||
cout<<"\nElement found at position : "<<pos;
|
||||
}
|
||||
else
|
||||
{
|
||||
cout<<"\nElement not found";
|
||||
}
|
||||
return pos;
|
||||
}
|
||||
|
||||
void Sort()
|
||||
{
|
||||
int i, j, pos;
|
||||
for(i=0; i<top; i++)
|
||||
{
|
||||
int min=data[i];
|
||||
for(j=i+1; j<top; j++)
|
||||
{
|
||||
if(data[j]<min)
|
||||
{
|
||||
pos=j;
|
||||
min=data[pos];
|
||||
}
|
||||
}
|
||||
|
||||
int temp=data[i];
|
||||
data[i]=data[pos];
|
||||
data[pos]=temp;
|
||||
}
|
||||
isSorted=true;
|
||||
}
|
||||
|
||||
void insert(int x)
|
||||
{
|
||||
if(!isSorted)
|
||||
{
|
||||
|
||||
if(top==49)
|
||||
{
|
||||
cout<<"\nOverflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
data[top]=x;
|
||||
top++;
|
||||
}
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
int pos=0;
|
||||
|
||||
for (int i = 0; i < top-1; i++)
|
||||
{
|
||||
if(data[i]<=x && x<=data[i+1])
|
||||
{
|
||||
pos=i+1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (pos==0)
|
||||
{
|
||||
pos=top-1;
|
||||
}
|
||||
|
||||
|
||||
|
||||
for (int i = top; i > pos; i--)
|
||||
{
|
||||
data[i]=data[i-1];
|
||||
}
|
||||
top++;
|
||||
data[pos]=x;
|
||||
}
|
||||
}
|
||||
|
||||
void Remove(int x)
|
||||
{
|
||||
int pos=Search(x);
|
||||
cout<<"\n"<<data[pos]<<" deleted";
|
||||
for (int i = pos; i < top; i++)
|
||||
{
|
||||
data[i]=data[i+1];
|
||||
}
|
||||
top--;
|
||||
}
|
||||
|
||||
void Show()
|
||||
{
|
||||
for (int i = 0; i < top; i++)
|
||||
{
|
||||
cout<<data[i]<<"\t";
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
int main()
|
||||
{
|
||||
list L;
|
||||
int choice;
|
||||
int x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1.Insert";
|
||||
cout<<"\n2.Delete";
|
||||
cout<<"\n3.Search";
|
||||
cout<<"\n4.Sort";
|
||||
cout<<"\n5.Print";
|
||||
cout<<"\n\nEnter Your Choice : ";
|
||||
cin>>choice;
|
||||
switch (choice)
|
||||
{
|
||||
case 1: cout<<"\nEnter the element to be inserted : ";
|
||||
cin>>x;
|
||||
L.insert(x);
|
||||
break;
|
||||
case 2: cout<<"\nEnter the element to be removed : ";
|
||||
cin>>x;
|
||||
L.Remove(x);
|
||||
break;
|
||||
case 3: cout<<"\nEnter the element to be searched : ";
|
||||
cin>>x;
|
||||
L.Search(x);
|
||||
break;
|
||||
case 4: L.Sort();
|
||||
break;
|
||||
case 5: L.Show();
|
||||
break;
|
||||
}
|
||||
}
|
||||
while(choice!=0);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,78 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int queue[10];
|
||||
int front=0;
|
||||
int rear=0;
|
||||
|
||||
void Enque(int x)
|
||||
{
|
||||
if(rear==10)
|
||||
{
|
||||
cout<<"\nOverflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
queue[rear++]=x;
|
||||
}
|
||||
}
|
||||
|
||||
void Deque()
|
||||
{
|
||||
if (front==rear)
|
||||
{
|
||||
cout<<"\nUnderflow";
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
cout<<"\n"<<queue[front++]<<" deleted";
|
||||
for (int i = front; i < rear; i++)
|
||||
{
|
||||
queue[i-front]=queue[i];
|
||||
}
|
||||
rear=rear-front;
|
||||
front=0;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
for (int i = front; i < rear; i++)
|
||||
{
|
||||
cout<<queue[i]<<"\t";
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int ch, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Enque";
|
||||
cout<<"\n2. Deque";
|
||||
cout<<"\n3. Print";
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
if (ch==1)
|
||||
{
|
||||
cout<<"\nInsert : ";
|
||||
cin>>x;
|
||||
Enque(x);
|
||||
}
|
||||
else if (ch==2)
|
||||
{
|
||||
Deque();
|
||||
}
|
||||
else if (ch==3)
|
||||
{
|
||||
show();
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
|
||||
node *front, *rear;
|
||||
|
||||
|
||||
void Enque(int x)
|
||||
{
|
||||
if (rear==NULL)
|
||||
{
|
||||
node *n= new node;
|
||||
n->val=x;
|
||||
n->next=NULL;
|
||||
rear=n;
|
||||
front=n;
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
|
||||
node *n = new node;
|
||||
n->val=x;
|
||||
n->next=NULL;
|
||||
rear->next=n;
|
||||
rear=n;
|
||||
}
|
||||
}
|
||||
|
||||
void Deque()
|
||||
{
|
||||
if (rear==front)
|
||||
{
|
||||
cout<<"\nUnderflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
node *t = front;
|
||||
cout<<"\n"<<t->val<<" deleted";
|
||||
front=front->next;
|
||||
delete t;
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
node *t=front;
|
||||
while(t!=NULL)
|
||||
{
|
||||
cout<<t->val<<"\t";
|
||||
t=t->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int ch, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Enque";
|
||||
cout<<"\n2. Deque";
|
||||
cout<<"\n3. Print";
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
if (ch==1)
|
||||
{
|
||||
cout<<"\nInsert : ";
|
||||
cin>>x;
|
||||
Enque(x);
|
||||
}
|
||||
else if (ch==2)
|
||||
{
|
||||
Deque();
|
||||
}
|
||||
else if (ch==3)
|
||||
{
|
||||
show();
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int *stack;
|
||||
int top=0, size;
|
||||
|
||||
void push(int x)
|
||||
{
|
||||
if(top==size)
|
||||
{
|
||||
cout<<"\nOverflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
stack[top++]=x;
|
||||
}
|
||||
}
|
||||
|
||||
void pop()
|
||||
{
|
||||
if (top==0)
|
||||
{
|
||||
cout<<"\nUnderflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
cout<<"\n"<<stack[--top]<<" deleted";
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
for (int i = 0; i < top; i++)
|
||||
{
|
||||
cout<<stack[i]<<"\n";
|
||||
}
|
||||
}
|
||||
|
||||
void topmost()
|
||||
{
|
||||
cout << "\nTopmost element: "<<stack[top-1];
|
||||
}
|
||||
int main()
|
||||
{
|
||||
cout<<"\nEnter Size of stack : ";
|
||||
cin>>size;
|
||||
stack = new int[size];
|
||||
int ch, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Push";
|
||||
cout<<"\n2. Pop";
|
||||
cout<<"\n3. Print";
|
||||
cout<<"\n4. Print topmost element:";
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
if (ch==1)
|
||||
{
|
||||
cout<<"\nInsert : ";
|
||||
cin>>x;
|
||||
push(x);
|
||||
}
|
||||
else if (ch==2)
|
||||
{
|
||||
pop();
|
||||
}
|
||||
else if (ch==3)
|
||||
{
|
||||
show();
|
||||
}
|
||||
else if(ch==4)
|
||||
{
|
||||
topmost();
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
|
||||
node *top;
|
||||
|
||||
void push(int x)
|
||||
{
|
||||
node *n = new node;
|
||||
n->val=x;
|
||||
n->next=top;
|
||||
top=n;
|
||||
}
|
||||
|
||||
void pop()
|
||||
{
|
||||
if (top==NULL)
|
||||
{
|
||||
cout<<"\nUnderflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
node *t = top;
|
||||
cout<<"\n"<<t->val<<" deleted";
|
||||
top=top->next;
|
||||
delete t;
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
node *t=top;
|
||||
while(t!=NULL)
|
||||
{
|
||||
cout<<t->val<<"\n";
|
||||
t=t->next;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int ch, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Push";
|
||||
cout<<"\n2. Pop";
|
||||
cout<<"\n3. Print";
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
if (ch==1)
|
||||
{
|
||||
cout<<"\nInsert : ";
|
||||
cin>>x;
|
||||
push(x);
|
||||
}
|
||||
else if (ch==2)
|
||||
{
|
||||
pop();
|
||||
}
|
||||
else if (ch==3)
|
||||
{
|
||||
show();
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,160 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
struct queue
|
||||
{
|
||||
node *t[100];
|
||||
int front;
|
||||
int rear;
|
||||
};
|
||||
|
||||
queue q;
|
||||
|
||||
|
||||
void enqueue(node *n)
|
||||
{
|
||||
q.t[q.rear++]=n;
|
||||
}
|
||||
|
||||
node * dequeue()
|
||||
{
|
||||
return (q.t[q.front++]);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void CreateTree(node *curr, node *n, int x, char pos)
|
||||
{
|
||||
if(n!=NULL)
|
||||
{
|
||||
char ch;
|
||||
cout<<"\nLeft or Right of "<<n->val<<" : ";
|
||||
cin>>ch;
|
||||
if(ch=='l')
|
||||
CreateTree(n, n->left, x, ch);
|
||||
else if(ch=='r')
|
||||
CreateTree(n, n->right, x, ch);
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
node *t=new node;
|
||||
t->val=x;
|
||||
t->left=NULL;
|
||||
t->right=NULL;
|
||||
if (pos=='l')
|
||||
{
|
||||
curr->left=t;
|
||||
}
|
||||
else if(pos=='r')
|
||||
{
|
||||
curr->right=t;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void BFT(node *n)
|
||||
{
|
||||
if(n!=NULL)
|
||||
{
|
||||
cout<<n->val<<" ";
|
||||
enqueue(n->left);
|
||||
enqueue(n->right);
|
||||
BFT(dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
void Pre(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
cout<<n->val<<" ";
|
||||
Pre(n->left);
|
||||
Pre(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void In(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
In(n->left);
|
||||
cout<<n->val<<" ";
|
||||
In(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void Post(node *n)
|
||||
{
|
||||
if (n!=NULL)
|
||||
{
|
||||
Post(n->left);
|
||||
Post(n->right);
|
||||
cout<<n->val<<" ";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
q.front=0;
|
||||
q.rear=0;
|
||||
int value;
|
||||
int ch;
|
||||
node *root=new node;
|
||||
cout<<"\nEnter the value of root node :";
|
||||
cin>>value;
|
||||
root->val=value;
|
||||
root->left=NULL;
|
||||
root->right=NULL;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Insert : ";
|
||||
cout<<"\n2. Breadth First";
|
||||
cout<<"\n3. Preorder Depth First";
|
||||
cout<<"\n4. Inorder Depth First";
|
||||
cout<<"\n5. Postorder Depth First";
|
||||
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
switch(ch)
|
||||
{
|
||||
case 1:
|
||||
int x;
|
||||
char pos;
|
||||
cout<<"\nEnter the value to be Inserted : ";
|
||||
cin>>x;
|
||||
cout<<"\nLeft or Right of Root : ";
|
||||
cin>>pos;
|
||||
if(pos=='l')
|
||||
CreateTree(root, root->left, x, pos);
|
||||
else if(pos=='r')
|
||||
CreateTree(root, root->right, x, pos);
|
||||
break;
|
||||
case 2:
|
||||
BFT(root);
|
||||
break;
|
||||
case 3:
|
||||
Pre(root);
|
||||
break;
|
||||
case 4:
|
||||
In(root);
|
||||
break;
|
||||
case 5:
|
||||
Post(root);
|
||||
break;
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<string.h>
|
||||
#include<stdbool.h>
|
||||
using namespace std;
|
||||
// structure definition
|
||||
typedef struct trie
|
||||
{
|
||||
struct trie *arr[26];
|
||||
bool isEndofWord;
|
||||
} trie;
|
||||
// create a new node for trie
|
||||
trie *createNode()
|
||||
{
|
||||
trie *nn = new trie();
|
||||
for (int i = 0; i < 26; i++)
|
||||
nn->arr[i] = NULL;
|
||||
nn->isEndofWord = false;
|
||||
return nn;
|
||||
}
|
||||
|
||||
// insert string into the trie
|
||||
void insert(trie *root, char* str)
|
||||
{
|
||||
for (int i = 0; i < strlen(str); i++)
|
||||
{
|
||||
int j = str[i] - 'a';
|
||||
if (root->arr[j])
|
||||
{
|
||||
root = root->arr[j];
|
||||
}
|
||||
else
|
||||
{
|
||||
root->arr[j] = createNode();
|
||||
root = root->arr[j];
|
||||
}
|
||||
}
|
||||
root->isEndofWord = true;
|
||||
}
|
||||
|
||||
// search a string exists inside the trie
|
||||
bool search(trie *root, char* str, int index)
|
||||
{
|
||||
if (index == strlen(str))
|
||||
{
|
||||
if (!root->isEndofWord)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
int j = str[index] - 'a';
|
||||
if (!root->arr[j])
|
||||
return false;
|
||||
return search(root->arr[j], str, index + 1);
|
||||
}
|
||||
/* removes the string if it is not a prefix of any other
|
||||
string, if it is then just sets the endofword to false, else
|
||||
removes the given string*/
|
||||
bool deleteString (trie *root, char* str, int index)
|
||||
{
|
||||
if (index == strlen(str))
|
||||
{
|
||||
if (!root->isEndofWord)
|
||||
return false;
|
||||
root->isEndofWord = false;
|
||||
for (int i = 0; i < 26; i++)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
int j = str[index] - 'a';
|
||||
if (!root->arr[j])
|
||||
return false;
|
||||
bool var = deleteString (root, str, index + 1);
|
||||
if (var)
|
||||
{
|
||||
root->arr[j] = NULL;
|
||||
if (root->isEndofWord)
|
||||
return false;
|
||||
else
|
||||
{
|
||||
int i;
|
||||
for (i = 0; i < 26; i++)
|
||||
if (root->arr[i])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
trie *root = createNode();
|
||||
insert(root, "hello");
|
||||
insert(root, "world");
|
||||
int a = search(root, "hello", 0);
|
||||
int b = search(root, "word", 0);
|
||||
printf("%d %d ", a, b);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
/* The difference between the pointer implementation of linked list and array implementation of linked list:
|
||||
1. The NULL is represented by -1;
|
||||
2. Limited size. (in the following case it is 100 nodes at max). But we can reuse the nodes that are to be deleted by again linking it bacj to the list.
|
||||
*/
|
||||
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
struct Node{
|
||||
int data;
|
||||
int next;
|
||||
};
|
||||
Node AvailArray[100]; //array that will act as nodes of a linked list.
|
||||
int head=-1;
|
||||
int avail=0;
|
||||
void initialise_list()
|
||||
{
|
||||
for(int i=0;i<=98;i++)
|
||||
{
|
||||
AvailArray[i].next=i+1;
|
||||
}
|
||||
AvailArray[99].next=-1; //indicating the end of the linked list.
|
||||
|
||||
}
|
||||
|
||||
int getnode() //This will return the index of the first free node present in the avail list
|
||||
{
|
||||
int NodeIndexToBeReturned=avail;
|
||||
avail=AvailArray[avail].next;
|
||||
return NodeIndexToBeReturned;
|
||||
}
|
||||
|
||||
void freeNode(int nodeToBeDeleted) //This function when called will delete the node with the index presented as an argument, and will put back that node into the array.
|
||||
{
|
||||
AvailArray[nodeToBeDeleted].next=avail;
|
||||
avail=nodeToBeDeleted;
|
||||
}
|
||||
|
||||
void insertAtTheBeginning(int data) //The function will insert the given data into the front of the linked list.
|
||||
{
|
||||
int newNode=getnode();
|
||||
AvailArray[newNode].data=data;
|
||||
AvailArray[newNode].next=head;
|
||||
head=newNode;
|
||||
|
||||
}
|
||||
|
||||
void insertAtTheEnd(int data)
|
||||
{
|
||||
int newNode=getnode();
|
||||
int temp=head;
|
||||
while(AvailArray[temp].next!=-1)
|
||||
{
|
||||
temp=AvailArray[temp].next;
|
||||
|
||||
}
|
||||
//temp is now pointing to the end node.
|
||||
AvailArray[newNode].data=data;
|
||||
AvailArray[newNode].next=-1;
|
||||
AvailArray[temp].next=newNode;
|
||||
}
|
||||
|
||||
|
||||
void display()
|
||||
{
|
||||
int temp=head;
|
||||
while(temp!=-1)
|
||||
{
|
||||
cout<<AvailArray[temp].data<<"->";
|
||||
temp=AvailArray[temp].next;
|
||||
}
|
||||
cout<<"-1"<<endl;;
|
||||
}
|
||||
|
||||
int main()
|
||||
{ initialise_list();
|
||||
int x,y,z;
|
||||
for(;;)
|
||||
{
|
||||
cout<<"1. Insert At The Beginning"<<endl;
|
||||
cout<<"2. Insert At The End"<<endl;
|
||||
cout<<"3. Display"<<endl;
|
||||
cout<<"4.Exit"<<endl;
|
||||
cout<<"Enter Your choice"<<endl;
|
||||
cin>>z;
|
||||
switch(z)
|
||||
{
|
||||
case 1:
|
||||
cout<<"Enter the number you want to enter"<<endl;
|
||||
cin>>x;
|
||||
insertAtTheBeginning(x);
|
||||
break;
|
||||
case 2:
|
||||
cout<<"Enter the number you want to enter"<<endl;
|
||||
cin>>y;
|
||||
insertAtTheEnd(y);
|
||||
break;
|
||||
case 3:
|
||||
cout<<"The linked list contains the following element in order"<<endl;
|
||||
display();
|
||||
break;
|
||||
case 4:
|
||||
exit(0);
|
||||
default:
|
||||
cout<<"The entered choice is not correct"<<endl;
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
//program to check whether a number is an armstrong number or not
|
||||
#include<iostream.h>
|
||||
#include<Math.h>
|
||||
int main()
|
||||
{
|
||||
int n,k,d,s=0;
|
||||
cout<<"Enter a number:";
|
||||
cin>>n;
|
||||
k=n;
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%10;
|
||||
s+=(int)pow(d,3);
|
||||
k/=10;
|
||||
}
|
||||
if(s==n)
|
||||
cout<<n<<"is an armstrong number";
|
||||
else
|
||||
cout<<n<<"is not an armstrong number";
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<limits.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
//Wrapper class for storing an edge
|
||||
class Edge{
|
||||
public: int src,dst,weight;
|
||||
};
|
||||
|
||||
//Wrapper class for storing a graph
|
||||
class Graph{
|
||||
public:
|
||||
int vertexNum,edgeNum;
|
||||
Edge* edges;
|
||||
|
||||
//Constructs a graph with V vertices and E edges
|
||||
Graph(int V,int E){
|
||||
this->vertexNum = V;
|
||||
this->edgeNum = E;
|
||||
this->edges =(Edge*) malloc(E * sizeof(Edge));
|
||||
}
|
||||
|
||||
//Adds the given edge to the graph
|
||||
void addEdge(int src, int dst, int weight){
|
||||
static int edgeInd = 0;
|
||||
if(edgeInd < this->edgeNum){
|
||||
Edge newEdge;
|
||||
newEdge.src = src;
|
||||
newEdge.dst = dst;
|
||||
newEdge.weight = weight;
|
||||
this->edges[edgeInd++] = newEdge;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
//Utility function to print distances
|
||||
void print(int dist[], int V){
|
||||
cout<<"\nVertex Distance"<<endl;
|
||||
for(int i = 0; i < V; i++){
|
||||
if( dist[i] != INT_MAX)
|
||||
cout<<i<<"\t"<<dist[i]<<endl;
|
||||
else
|
||||
cout<<i<<"\tINF"<<endl;
|
||||
}
|
||||
}
|
||||
|
||||
//The main function that finds the shortest path from given source
|
||||
//to all other vertices using Bellman-Ford.It also detects negative
|
||||
//weight cycle
|
||||
void BellmanFord(Graph graph, int src){
|
||||
int V = graph.vertexNum;
|
||||
int E = graph.edgeNum;
|
||||
int dist[V];
|
||||
|
||||
//Initialize distances array as INF for all except source
|
||||
//Intialize source as zero
|
||||
for(int i=0; i<V; i++)
|
||||
dist[i] = INT_MAX;
|
||||
dist[src] = 0;
|
||||
|
||||
//Calculate shortest path distance from source to all edges
|
||||
//A path can contain maximum (|V|-1) edges
|
||||
for(int i=0; i<=V-1; i++)
|
||||
for(int j = 0; j<E; j++){
|
||||
int u = graph.edges[j].src;
|
||||
int v = graph.edges[j].dst;
|
||||
int w = graph.edges[j].weight;
|
||||
|
||||
if(dist[u]!=INT_MAX && dist[u] + w < dist[v])
|
||||
dist[v] = dist[u] + w;
|
||||
}
|
||||
|
||||
//Iterate inner loop once more to check for negative cycle
|
||||
for(int j = 0; j<E; j++){
|
||||
int u = graph.edges[j].src;
|
||||
int v = graph.edges[j].dst;
|
||||
int w = graph.edges[j].weight;
|
||||
|
||||
if(dist[u]!=INT_MAX && dist[u] + w < dist[v]){
|
||||
cout<<"Graph contains negative weight cycle. Hence, shortest distance not guaranteed."<<endl;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
print(dist, V);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
//Driver Function
|
||||
int main(){
|
||||
int V,E,gsrc;
|
||||
int src,dst,weight;
|
||||
cout<<"Enter number of vertices: ";
|
||||
cin>>V;
|
||||
cout<<"Enter number of edges: ";
|
||||
cin>>E;
|
||||
Graph G(V,E);
|
||||
for(int i=0; i<E; i++){
|
||||
cout<<"\nEdge "<<i+1<<"\nEnter source: ";
|
||||
cin>>src;
|
||||
cout<<"Enter destination: ";
|
||||
cin>>dst;
|
||||
cout<<"Enter weight: ";
|
||||
cin>>weight;
|
||||
G.addEdge(src, dst, weight);
|
||||
}
|
||||
cout<<"\nEnter source: ";
|
||||
cin>>gsrc;
|
||||
BellmanFord(G,gsrc);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
/*Given a rod of length n inches and an array of prices that
|
||||
contains prices of all pieces of size smaller than n. Determine
|
||||
the maximum value obtainable by cutting up the rod and selling
|
||||
the pieces.*/
|
||||
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
int cutrod(int p[],int n)
|
||||
{
|
||||
int r[n+1];
|
||||
r[0]=0;
|
||||
for(int j=0;j<n;j++)
|
||||
{
|
||||
int q=INT_MIN;
|
||||
for(int i=0;i<=j;i++)
|
||||
{
|
||||
q = max(q,p[i]+r[j-i]);
|
||||
}
|
||||
r[j+1]=q;
|
||||
}
|
||||
return r[n];
|
||||
}
|
||||
int main()
|
||||
{
|
||||
int price[]={1,5,8,9,10,17,17,20,24,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50};
|
||||
cout<<cutrod(price,30);
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
/* Given two strings str1 & str2
|
||||
* and below operations that can
|
||||
* be performed on str1. Find
|
||||
* minimum number of edits
|
||||
* (operations) required to convert
|
||||
* 'str1' into 'str2'/
|
||||
* a. Insert
|
||||
* b. Remove
|
||||
* c. Replace
|
||||
* All of the above operations are
|
||||
* of equal cost
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
using namespace std;
|
||||
|
||||
int min(int x, int y, int z){
|
||||
return min(min(x,y), z);
|
||||
}
|
||||
|
||||
/* A Naive recursive C++ program to find
|
||||
* minimum number of operations to convert
|
||||
* str1 to str2.
|
||||
* O(3^m)
|
||||
*/
|
||||
int editDist(string str1, string str2, int m, int n) {
|
||||
if(m == 0) return n;
|
||||
if(n == 0) return m;
|
||||
|
||||
//If last characters are same then continue
|
||||
//for the rest of them.
|
||||
if(str1[m-1] == str2[n-1])
|
||||
return editDist(str1, str2, m-1, n-1);
|
||||
|
||||
//If last not same, then 3 possibilities
|
||||
//a.Insert b.Remove c. Replace
|
||||
//Get min of three and continue for rest.
|
||||
return 1 + min ( editDist(str1, str2, m, n-1),
|
||||
editDist(str1, str2, m-1, n),
|
||||
editDist(str1, str2, m-1, n-1)
|
||||
);
|
||||
}
|
||||
|
||||
/* A DP based program
|
||||
* O(m x n)
|
||||
*/
|
||||
int editDistDP(string str1, string str2, int m, int n) {
|
||||
|
||||
//Create Table for SubProblems
|
||||
int dp[m+1][n+1];
|
||||
|
||||
//Fill d[][] in bottom up manner
|
||||
for(int i=0; i<=m; i++) {
|
||||
for(int j=0; j<=n; j++) {
|
||||
//If str1 empty. Then add all of str2
|
||||
if(i==0)
|
||||
dp[i][j] = j;
|
||||
|
||||
//If str2 empty. Then add all of str1
|
||||
else if(j==0)
|
||||
dp[i][j] = i;
|
||||
|
||||
//If character same. Recur for remaining
|
||||
else if(str1[i-1] == str2[j-1])
|
||||
dp[i][j] = dp[i-1][j-1];
|
||||
|
||||
else
|
||||
dp[i][j] = 1 + min(dp[i][j-1],//Insert
|
||||
dp[i-1][j],//Remove
|
||||
dp[i-1][j-1]//Replace
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return dp[m][n];
|
||||
}
|
||||
|
||||
int main() {
|
||||
string str1 = "sunday";
|
||||
string str2 = "saturday";
|
||||
|
||||
cout << editDist(str1, str2, str1.length(), str2.length()) << endl;
|
||||
cout << editDistDP(str1, str2, str1.length(), str2.length()) << endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
int fib(int n){
|
||||
int res[n+1];
|
||||
res[0] = 0; res[1] = 1;
|
||||
for(int i=2;i<=n;i++){
|
||||
res[i] = res[i-1] + res[i-2];
|
||||
}
|
||||
return res[n];
|
||||
}
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int n;
|
||||
cout<<"Enter n: ";
|
||||
cin>>n;
|
||||
cout<<"Fibonacci number is ";
|
||||
cout<<fib(n)<<endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
int arr[1000000];
|
||||
int fib(int n){
|
||||
if(arr[n]==-1){
|
||||
if(n<=1)
|
||||
arr[n] = n;
|
||||
else
|
||||
arr[n] = fib(n-1) + fib(n-2);
|
||||
}
|
||||
return arr[n];
|
||||
}
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int n;
|
||||
cout<<"Enter n: ";
|
||||
cin>>n;
|
||||
for (int i = 0; i < n+1; ++i)
|
||||
{
|
||||
arr[i] = -1;
|
||||
}
|
||||
cout<<"Fibonacci number is "<<fib(n)<<endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,106 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<limits.h>
|
||||
#include<string.h>
|
||||
|
||||
using namespace std;
|
||||
|
||||
//Wrapper class for storing a graph
|
||||
class Graph{
|
||||
public:
|
||||
int vertexNum;
|
||||
int** edges;
|
||||
|
||||
//Constructs a graph with V vertices and E edges
|
||||
Graph(int V){
|
||||
this->vertexNum = V;
|
||||
this->edges =(int**) malloc(V * sizeof(int*));
|
||||
for(int i=0; i<V; i++){
|
||||
this->edges[i] = (int*) malloc(V * sizeof(int));
|
||||
for(int j=0; j<V; j++)
|
||||
this->edges[i][j] = INT_MAX;
|
||||
this->edges[i][i] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
//Adds the given edge to the graph
|
||||
void addEdge(int src, int dst, int weight){
|
||||
this->edges[src][dst] = weight;
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
|
||||
//Utility function to print distances
|
||||
void print(int dist[], int V){
|
||||
cout<<"\nThe Distance matrix for Floyd - Warshall"<<endl;
|
||||
for(int i = 0; i < V; i++){
|
||||
for(int j=0; j<V; j++){
|
||||
|
||||
if(dist[i*V+j] != INT_MAX)
|
||||
cout<<dist[i*V+j]<<"\t";
|
||||
else
|
||||
cout<<"INF"<<"\t";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
}
|
||||
|
||||
//The main function that finds the shortest path from a vertex
|
||||
//to all other vertices using Floyd-Warshall Algorithm.
|
||||
void FloydWarshall(Graph graph){
|
||||
int V = graph.vertexNum;
|
||||
int dist[V][V];
|
||||
|
||||
//Initialise distance array
|
||||
for(int i=0; i<V; i++)
|
||||
for(int j=0; j<V; j++)
|
||||
dist[i][j] = graph.edges[i][j];
|
||||
|
||||
|
||||
//Calculate distances
|
||||
for(int k=0; k<V; k++)
|
||||
//Choose an intermediate vertex
|
||||
|
||||
for(int i=0; i<V; i++)
|
||||
//Choose a source vertex for given intermediate
|
||||
|
||||
for(int j=0; j<V; j++)
|
||||
//Choose a destination vertex for above source vertex
|
||||
|
||||
if(dist[i][k] != INT_MAX && dist[k][j] != INT_MAX && dist[i][k] + dist[k][j] < dist[i][j])
|
||||
//If the distance through intermediate vertex is less than direct edge then update value in distance array
|
||||
dist[i][j] = dist[i][k] + dist[k][j];
|
||||
|
||||
|
||||
//Convert 2d array to 1d array for print
|
||||
int dist1d[V*V];
|
||||
for(int i=0; i<V; i++)
|
||||
for(int j=0; j<V; j++)
|
||||
dist1d[i*V+j] = dist[i][j];
|
||||
|
||||
print(dist1d,V);
|
||||
}
|
||||
|
||||
//Driver Function
|
||||
int main(){
|
||||
int V,E;
|
||||
int src,dst,weight;
|
||||
cout<<"Enter number of vertices: ";
|
||||
cin>>V;
|
||||
cout<<"Enter number of edges: ";
|
||||
cin>>E;
|
||||
Graph G(V);
|
||||
for(int i=0; i<E; i++){
|
||||
cout<<"\nEdge "<<i+1<<"\nEnter source: ";
|
||||
cin>>src;
|
||||
cout<<"Enter destination: ";
|
||||
cin>>dst;
|
||||
cout<<"Enter weight: ";
|
||||
cin>>weight;
|
||||
G.addEdge(src, dst, weight);
|
||||
}
|
||||
FloydWarshall(G);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
//Longest common subsequence - Dynamic Programming
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
void Print(int trace[20][20], int m, int n, string a)
|
||||
{
|
||||
if (m==0 || n==0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if (trace[m][n]==1)
|
||||
{
|
||||
Print(trace, m-1, n-1, a);
|
||||
cout<<a[m-1];
|
||||
}
|
||||
else if(trace[m][n]==2)
|
||||
{
|
||||
Print(trace, m-1,n, a);
|
||||
}
|
||||
else if (trace[m][n]==3)
|
||||
{
|
||||
Print(trace, m,n-1, a);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
int lcs(string a, string b)
|
||||
{
|
||||
int m = a.length(), n = b.length();
|
||||
int res[m+1][n+1];
|
||||
int trace[20][20];
|
||||
|
||||
// fills up the arrays with zeros.
|
||||
for (int i = 0; i < m+1; i++)
|
||||
{
|
||||
for (int j = 0; j < n+1; j++)
|
||||
{
|
||||
res[i][j] = 0;
|
||||
trace[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < m+1; ++i)
|
||||
{
|
||||
for (int j = 0; j < n+1; ++j)
|
||||
{
|
||||
if(i==0||j==0)
|
||||
{
|
||||
res[i][j] = 0;
|
||||
trace[i][j]=0;
|
||||
}
|
||||
|
||||
else if(a[i-1]==b[j-1])
|
||||
{
|
||||
res[i][j] = 1 + res[i-1][j-1];
|
||||
trace[i][j]=1; // 1 means trace the matrix in upper left diagonal direction.
|
||||
}
|
||||
else
|
||||
{
|
||||
if (res[i-1][j]>res[i][j-1])
|
||||
{
|
||||
res[i][j]=res[i-1][j];
|
||||
trace[i][j]=2; // 2 means trace the matrix in upwards direction.
|
||||
}
|
||||
else
|
||||
{
|
||||
res[i][j]=res[i][j-1];
|
||||
trace[i][j]=3; // means trace the matrix in left direction.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Print(trace, m, n, a);
|
||||
return res[m][n];
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
string a,b;
|
||||
cin>>a>>b;
|
||||
cout<<lcs(a,b);
|
||||
return 0;
|
||||
}
|
||||
BIN
Graph/.DS_Store
vendored
BIN
Graph/.DS_Store
vendored
Binary file not shown.
@@ -1,60 +0,0 @@
|
||||
#include<bits/stdc++.h>
|
||||
using namespace std;
|
||||
class graph{
|
||||
int v;
|
||||
list<int> *adj;
|
||||
public:
|
||||
graph(int v);
|
||||
void addedge(int src,int dest);
|
||||
void printgraph();
|
||||
void bfs(int s);
|
||||
};
|
||||
graph::graph(int v){
|
||||
this->v = v;
|
||||
this->adj = new list<int>[v];
|
||||
}
|
||||
void graph::addedge(int src,int dest){
|
||||
src--;dest--;
|
||||
adj[src].push_back(dest);
|
||||
//adj[dest].push_back(src);
|
||||
}
|
||||
void graph::printgraph(){
|
||||
for(int i=0;i<this->v;i++){
|
||||
cout<<"Adjacency list of vertex "<<i+1<<" is \n";
|
||||
list<int>::iterator it;
|
||||
for(it=adj[i].begin();it!=adj[i].end();++it){
|
||||
cout<<*it+1<<" ";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
}
|
||||
void graph::bfs(int s){
|
||||
bool *visited = new bool[this->v+1];
|
||||
memset(visited,false,sizeof(bool)*(this->v+1));
|
||||
visited[s]=true;
|
||||
list<int> q;
|
||||
q.push_back(s);
|
||||
list<int>::iterator it;
|
||||
while(!q.empty()){
|
||||
int u = q.front();
|
||||
cout<<u<<" ";
|
||||
q.pop_front();
|
||||
for(it=adj[u].begin();it!=adj[u].end();++it){
|
||||
if(visited[*it]==false){
|
||||
visited[*it] = true;
|
||||
q.push_back(*it);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
int main(){
|
||||
graph g(4);
|
||||
g.addedge(1,2);
|
||||
g.addedge(2,3);
|
||||
g.addedge(3,4);
|
||||
g.addedge(1,4);
|
||||
g.addedge(1,3);
|
||||
//g.printgraph();
|
||||
g.bfs(2);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
#include <bits/stdc++.h>
|
||||
using namespace std;
|
||||
int v = 4;
|
||||
void DFSUtil_(int graph[4][4],bool visited[],int s){
|
||||
visited[s] = true;
|
||||
cout<<s<<" ";
|
||||
for(int i=0;i<v;i++){
|
||||
if(graph[s][i]==1&&visited[i]==false){
|
||||
DFSUtil_(graph,visited,i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void DFS_(int graph[4][4],int s){
|
||||
bool visited[v];
|
||||
memset(visited,0,sizeof(visited));
|
||||
DFSUtil_(graph,visited,s);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int graph[4][4] = {{0,1,1,0},{0,0,1,0},{1,0,0,1},{0,0,0,1}};
|
||||
cout<<"DFS: ";
|
||||
DFS_(graph,2);
|
||||
cout<<endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
#include <queue>
|
||||
#include <vector>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
#define INF 10000010
|
||||
vector < pair <int,int> > graph[5*100001];
|
||||
int dis[5*100001];
|
||||
int dij(vector <pair<int,int> > * v,int s,int * dis) {
|
||||
priority_queue < pair <int,int> , vector < pair <int,int> >,greater < pair <int,int> > > pq;
|
||||
// source distance to zero.
|
||||
pq.push(make_pair(0,s));
|
||||
dis[s] = 0;
|
||||
int u;
|
||||
while(!pq.empty()) {
|
||||
u = (pq.top()).second;
|
||||
pq.pop();
|
||||
for( vector <pair <int,int> > :: iterator it = v[u].begin(); it != v[u].end();it++) {
|
||||
if(dis[u] + it->first < dis[it->second]) {
|
||||
dis[it->second] = dis[u] + it->first;
|
||||
pq.push(make_pair(dis[it->second],it->second));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
int main() {
|
||||
int m,n,l,x,y,s;
|
||||
// n--> number of nodes , m --> number of edges
|
||||
cin>>n>>m;
|
||||
for(int i = 0;i < m;i++) {
|
||||
// input edges.
|
||||
scanf("%d%d%d",&x,&y,&l);
|
||||
graph[x].push_back(make_pair(l,y));
|
||||
graph[y].push_back(make_pair(l,x)); // comment this line for directed graph
|
||||
}
|
||||
// start node.
|
||||
scanf("%d",&s);
|
||||
// intialise all distances to infinity.
|
||||
for(int i = 1;i <= n;i++)
|
||||
dis[i] = INF;
|
||||
dij(graph,s,dis);
|
||||
|
||||
for(int i = 1;i <= n;i++)
|
||||
if(dis[i] == INF)
|
||||
cout<<"-1 ";
|
||||
else
|
||||
cout<<dis[i]<<" ";
|
||||
return 0;
|
||||
}
|
||||
@@ -1,92 +0,0 @@
|
||||
#include "bits/stdc++.h"
|
||||
//#include <boost/multiprecision/cpp_int.hpp>
|
||||
//using namespace boost::multiprecision;
|
||||
const int mx = 1e6+5;
|
||||
const long int inf = 2e9;
|
||||
typedef long long ll;
|
||||
#define rep(i,n) for(i=0;i<n;i++)
|
||||
#define repp(i,a,b) for(i=a;i<=b;i++)
|
||||
#define pii pair<int,int>
|
||||
#define vpii vector< pii >
|
||||
#define vi vector<int>
|
||||
#define vll vector<ll>
|
||||
#define r(x) scanf("%d",&x)
|
||||
#define rs(s) scanf("%s",s)
|
||||
#define gc getchar_unlocked
|
||||
#define pc putchar_unlocked
|
||||
#define mp make_pair
|
||||
#define pb push_back
|
||||
#define lb lower_bound
|
||||
#define ub upper_bound
|
||||
#define endl "\n"
|
||||
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
|
||||
using namespace std;
|
||||
void in(int &x)
|
||||
{
|
||||
register int c = gc(); x = 0; int neg = 0;
|
||||
for(;((c<48 || c>57) && c != '-');c = gc());if(c=='-') {neg=1;c=gc();} for(;c>47 && c<58;c = gc()) {x = (x<<1) + (x<<3) + c - 48;}
|
||||
if(neg) x=-x;
|
||||
}
|
||||
void out (int n) { int N = n, rev, count = 0;rev = N; if (N == 0) { pc('0'); return ;} while ((rev % 10) == 0) { count++; rev /= 10;} rev = 0;while (N != 0) { rev = (rev<<3) + (rev<<1) + N % 10; N /= 10;}while (rev != 0) { pc(rev % 10 + '0'); rev /= 10;}
|
||||
while (count--) pc('0');
|
||||
}
|
||||
ll parent[mx],arr[mx],node,edge;
|
||||
vector<pair<ll,pair<ll,ll>>>v;
|
||||
void initial()
|
||||
{
|
||||
int i;
|
||||
rep(i,node+edge)
|
||||
parent[i] = i;
|
||||
}
|
||||
int root(int i)
|
||||
{
|
||||
while(parent[i] != i)
|
||||
{
|
||||
parent[i] = parent[parent[i]];
|
||||
i = parent[i];
|
||||
}
|
||||
return i;
|
||||
}
|
||||
void join(int x,int y)
|
||||
{
|
||||
int root_x = root(x); //Disjoint set union by rank
|
||||
int root_y = root(y);
|
||||
parent[root_x] = root_y;
|
||||
}
|
||||
ll kruskal()
|
||||
{
|
||||
ll mincost=0,i,x,y;
|
||||
rep(i,edge)
|
||||
{
|
||||
x = v[i].second.first;
|
||||
y = v[i].second.second;
|
||||
if(root(x) != root(y))
|
||||
{
|
||||
mincost += v[i].first;
|
||||
join(x,y);
|
||||
}
|
||||
}
|
||||
return mincost;
|
||||
}
|
||||
int main(){
|
||||
fast;
|
||||
while(1)
|
||||
{
|
||||
int i,j,from,to,cost,totalcost=0;
|
||||
cin>>node>>edge; //Enter the nodes and edges
|
||||
if(node==0 && edge==0) break; //Enter 0 0 to break out
|
||||
initial(); //Initialise the parent array
|
||||
rep(i,edge)
|
||||
{
|
||||
cin>>from>>to>>cost;
|
||||
v.pb(mp(cost,mp(from,to)));
|
||||
totalcost += cost;
|
||||
}
|
||||
sort(v.begin(),v.end());
|
||||
// rep(i,v.size())
|
||||
// cout<<v[i].first<<" ";
|
||||
cout<<kruskal()<<endl;
|
||||
v.clear();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
BIN
Greedy Algorithms/.DS_Store
vendored
BIN
Greedy Algorithms/.DS_Store
vendored
Binary file not shown.
@@ -1,97 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct Item
|
||||
{
|
||||
int weight;
|
||||
int profit;
|
||||
};
|
||||
|
||||
|
||||
float profitPerUnit(Item x)
|
||||
{
|
||||
return (float)x.profit/(float)x.weight;
|
||||
}
|
||||
|
||||
int partition (Item arr[], int low, int high)
|
||||
{
|
||||
Item pivot = arr[high]; // pivot
|
||||
int i = (low - 1); // Index of smaller element
|
||||
|
||||
for (int j = low; j <high; j++)
|
||||
{
|
||||
// If current element is smaller than or
|
||||
// equal to pivot
|
||||
if (profitPerUnit(arr[j]) <= profitPerUnit(pivot))
|
||||
{
|
||||
i++; // increment index of smaller element
|
||||
Item temp=arr[i];
|
||||
arr[i]=arr[j];
|
||||
arr[j]=temp;
|
||||
}
|
||||
}
|
||||
Item temp=arr[i+1];
|
||||
arr[i+1]=arr[high];
|
||||
arr[high]=temp;
|
||||
return (i + 1);
|
||||
}
|
||||
|
||||
|
||||
void quickSort(Item arr[], int low, int high)
|
||||
{
|
||||
if (low < high)
|
||||
{
|
||||
|
||||
int p= partition(arr, low, high);
|
||||
|
||||
quickSort(arr, low, p - 1);
|
||||
quickSort(arr, p + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
cout<<"\nEnter the capacity of the knapsack : ";
|
||||
float capacity;
|
||||
cin>>capacity;
|
||||
cout<<"\n Enter the number of Items : ";
|
||||
int n;
|
||||
cin>>n;
|
||||
Item itemArray[n];
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
cout<<"\nEnter the weight and profit of item "<<i+1<<" : ";
|
||||
cin>>itemArray[i].weight;
|
||||
cin>>itemArray[i].profit;
|
||||
}
|
||||
|
||||
quickSort(itemArray, 0, n-1);
|
||||
|
||||
// show(itemArray, n);
|
||||
|
||||
float maxProfit=0;
|
||||
int i=n;
|
||||
while(capacity>0 && --i>=0)
|
||||
{
|
||||
if(capacity>=itemArray[i].weight)
|
||||
{
|
||||
maxProfit+=itemArray[i].profit;
|
||||
capacity-=itemArray[i].weight;
|
||||
cout<<"\n\t"<<itemArray[i].weight<<"\t"<<itemArray[i].profit;
|
||||
}
|
||||
else
|
||||
{
|
||||
maxProfit+=profitPerUnit(itemArray[i])*capacity;
|
||||
cout<<"\n\t"<<capacity<<"\t"<<profitPerUnit(itemArray[i])*capacity;
|
||||
capacity=0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
cout<<"\nMax Profit : "<<maxProfit;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,82 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
#define V 4
|
||||
#define INFINITY 99999
|
||||
|
||||
int graph[V][V] = {
|
||||
{0, 5, 1, 2},
|
||||
{5, 0, 3, 3},
|
||||
{1, 3, 0, 4},
|
||||
{2, 3, 4, 0}
|
||||
};
|
||||
|
||||
|
||||
struct mst
|
||||
{
|
||||
bool visited;
|
||||
int key;
|
||||
int near;
|
||||
};
|
||||
|
||||
mst MST_Array[V];
|
||||
|
||||
void initilize()
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
MST_Array[i].visited=false;
|
||||
MST_Array[i].key=INFINITY; // considering INFINITY as inifinity
|
||||
MST_Array[i].near=i;
|
||||
}
|
||||
|
||||
MST_Array[0].key=0;
|
||||
}
|
||||
|
||||
void updateNear()
|
||||
{
|
||||
for (int v = 0; v < V; v++)
|
||||
{
|
||||
int min=INFINITY;
|
||||
int minIndex=0;
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (MST_Array[i].key<min && MST_Array[i].visited==false && MST_Array[i].key!=INFINITY)
|
||||
{
|
||||
min=MST_Array[i].key;
|
||||
minIndex=i;
|
||||
}
|
||||
}
|
||||
|
||||
MST_Array[minIndex].visited=true;
|
||||
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
if (graph[minIndex][i]!=0 && graph[minIndex][i]<INFINITY)
|
||||
{
|
||||
if (graph[minIndex][i]<MST_Array[i].key)
|
||||
{
|
||||
MST_Array[i].key=graph[minIndex][i];
|
||||
MST_Array[i].near=minIndex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
{
|
||||
cout<<i<<" - "<<MST_Array[i].near<<"\t"<<graph[i][MST_Array[i].near]<<"\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
initilize();
|
||||
updateNear();
|
||||
show();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<math.h>
|
||||
using namespace std;
|
||||
|
||||
struct Node {
|
||||
int data;
|
||||
struct Node *next;
|
||||
} *head[100],*curr;
|
||||
|
||||
void init() {
|
||||
for(int i=0;i<100;i++)
|
||||
head[i]=NULL;
|
||||
}
|
||||
|
||||
void add(int x,int h) {
|
||||
struct Node *temp = new Node;
|
||||
temp->data = x;
|
||||
temp->next = NULL;
|
||||
if(!head[h]) {
|
||||
head[h] = temp;
|
||||
curr = head[h];
|
||||
}
|
||||
else {
|
||||
curr=head[h];
|
||||
while(curr->next)
|
||||
curr = curr->next;
|
||||
curr->next = temp;
|
||||
}
|
||||
}
|
||||
|
||||
void display(int mod) {
|
||||
struct Node *temp;
|
||||
int i;
|
||||
for(i=0;i<mod;i++) {
|
||||
if(!head[i]) {
|
||||
cout<<"Key "<<i<<" is empty"<<endl;
|
||||
}
|
||||
else {
|
||||
cout<<"Key "<<i<<" has values = ";
|
||||
temp = head[i];
|
||||
while(temp->next) {
|
||||
cout<<temp->data<<" ";
|
||||
temp=temp->next;
|
||||
}
|
||||
cout<<temp->data;
|
||||
cout<<endl;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int hash(int x,int mod) {
|
||||
return x%mod;
|
||||
}
|
||||
|
||||
void find(int x,int h) {
|
||||
struct Node *temp =head[h];
|
||||
if(!head[h]) {
|
||||
cout<<"Element not found";
|
||||
return;
|
||||
}
|
||||
while(temp->data !=x && temp->next)
|
||||
temp=temp->next;
|
||||
if(temp->next)
|
||||
cout<<"Element found";
|
||||
else{
|
||||
if(temp->data == x)
|
||||
cout<<"Element found";
|
||||
else
|
||||
cout<< "Element not found";
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
init();
|
||||
int c,x,mod,h;
|
||||
cout<<"Enter the size of Hash Table. = ";
|
||||
cin>>mod;
|
||||
bool loop = true;
|
||||
while(loop) {
|
||||
cout<<endl;
|
||||
cout<<"PLEASE CHOOSE -"<<endl;
|
||||
cout<<"1. Add element."<<endl;
|
||||
cout<<"2. Find element."<<endl;
|
||||
cout<<"3. Generate Hash."<<endl;
|
||||
cout<<"4. Display Hash table."<<endl;
|
||||
cout<<"5. Exit."<<endl;
|
||||
cin>>c;
|
||||
switch(c) {
|
||||
case 1:
|
||||
cout<<"Enter element to add = ";
|
||||
cin>>x;
|
||||
h = hash(x,mod);
|
||||
h = fabs(h);
|
||||
add(x,h);
|
||||
break;
|
||||
case 2:
|
||||
cout<<"Enter element to search = ";
|
||||
cin>>x;
|
||||
h = hash(x,mod);
|
||||
find(x,h);
|
||||
break;
|
||||
case 3:
|
||||
cout<<"Enter element to generate hash = ";
|
||||
cin>>x;
|
||||
cout<<"Hash of "<<x<<" is = "<<hash(x,mod);
|
||||
break;
|
||||
case 4:
|
||||
display(mod);
|
||||
break;
|
||||
default:
|
||||
loop = false;
|
||||
break;
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
/*add(1,&head1);
|
||||
add(2,&head1);
|
||||
add(3,&head2);
|
||||
add(5,&head1);
|
||||
display(&head1);
|
||||
display(&head2);*/
|
||||
return 0;
|
||||
}
|
||||
21
LICENSE
Normal file
21
LICENSE
Normal file
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 TheAlgorithms
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,31 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
int main(){
|
||||
int n,k;
|
||||
cout<<"Enter size of array=\t";
|
||||
cin>>n;
|
||||
cout<<"Enter Number of indeces u want to rotate the array to left=\t";
|
||||
cin>>k;
|
||||
int a[n];
|
||||
cout<<"Enter elements of array=\t";
|
||||
for(int i=0;i<n;i++){
|
||||
cin>>a[i];
|
||||
}
|
||||
int temp=0;
|
||||
for(int i=0;i<k;i++){
|
||||
temp=a[0];
|
||||
for(int j=0;j<n;j++){
|
||||
if(j==n-1){
|
||||
a[n-1]=temp;
|
||||
}
|
||||
else{
|
||||
a[j]=a[j+1];
|
||||
}
|
||||
}
|
||||
}cout<<"Your rotated array is=\t";
|
||||
for(int j=0;j<n;j++){
|
||||
cout<<a[j]<<" ";
|
||||
}
|
||||
getchar();
|
||||
return 0;
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main(){
|
||||
int n,k;
|
||||
cout<<"Enter size of array=\t";
|
||||
cin>>n;
|
||||
cout<<"Enter Number of indices u want to rotate the array to right=\t";
|
||||
cin>>k;
|
||||
int a[n];
|
||||
cout<<"Enter elements of array=\t";
|
||||
for(int i=0;i<n;i++)
|
||||
cin>>a[i];
|
||||
int temp=0;
|
||||
for(int i=0;i<k;i++){
|
||||
temp=a[n-1];
|
||||
for(int j=n-1;j>=0;j--){
|
||||
if(j==0){
|
||||
a[j]=temp;
|
||||
}
|
||||
else{
|
||||
a[j]=a[j-1];}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
cout<<"Your rotated array is=\t";
|
||||
for(int i=0;i<n;i++){
|
||||
cout<<a[i]<<" ";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,109 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *next;
|
||||
};
|
||||
|
||||
node *start;
|
||||
|
||||
void insert(int x)
|
||||
{
|
||||
node *t=start;
|
||||
|
||||
if (start!=NULL)
|
||||
{
|
||||
while(t->next!=start)
|
||||
{
|
||||
t=t->next;
|
||||
}
|
||||
node *n= new node;
|
||||
t->next=n;
|
||||
n->val=x;
|
||||
n->next=start;
|
||||
}
|
||||
else
|
||||
{
|
||||
node *n= new node;
|
||||
n->val=x;
|
||||
start=n;
|
||||
n->next=start;
|
||||
}
|
||||
}
|
||||
|
||||
void remove(int x)
|
||||
{
|
||||
node *t=start;
|
||||
node *p;
|
||||
while(t->val!=x)
|
||||
{
|
||||
p=t;
|
||||
t=t->next;
|
||||
}
|
||||
p->next=t->next;
|
||||
delete t;
|
||||
}
|
||||
|
||||
void search(int x)
|
||||
{
|
||||
node *t= start;
|
||||
int found =0;
|
||||
while(t->next!=start)
|
||||
{
|
||||
if(t->val==x)
|
||||
{
|
||||
cout<<"\nFound";
|
||||
found=1;
|
||||
break;
|
||||
}
|
||||
t=t->next;
|
||||
}
|
||||
if(found==0)
|
||||
{
|
||||
cout<<"\nNot Found";
|
||||
}
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
node *t=start;
|
||||
do
|
||||
{
|
||||
cout<<t->val<<"\t";
|
||||
t=t->next;
|
||||
}
|
||||
while(t!=start);
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int choice, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Insert";
|
||||
cout<<"\n2. Delete";
|
||||
cout<<"\n3. Search";
|
||||
cout<<"\n4. Print";
|
||||
cout<<"\n\nEnter you choice : ";
|
||||
cin>>choice;
|
||||
switch (choice)
|
||||
{
|
||||
case 1 : cout<<"\nEnter the element to be inserted : ";
|
||||
cin>>x;
|
||||
insert(x); break;
|
||||
case 2 : cout<<"\nEnter the element to be removed : ";
|
||||
cin>>x;
|
||||
remove(x); break;
|
||||
case 3 : cout<<"\nEnter the element to be searched : ";
|
||||
cin>>x;
|
||||
search(x); break;
|
||||
case 4 : show(); break;
|
||||
}
|
||||
}
|
||||
while(choice!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int queue[10];
|
||||
int front=0;
|
||||
int rear=0;
|
||||
int count=0;
|
||||
|
||||
void Enque(int x)
|
||||
{
|
||||
if(count==10)
|
||||
{
|
||||
cout<<"\nOverflow";
|
||||
}
|
||||
else
|
||||
{
|
||||
queue[rear]=x;
|
||||
rear=(rear+1)%10;
|
||||
count++;
|
||||
}
|
||||
}
|
||||
|
||||
void Deque()
|
||||
{
|
||||
if (front==rear)
|
||||
{
|
||||
cout<<"\nUnderflow";
|
||||
}
|
||||
|
||||
else
|
||||
{
|
||||
cout<<"\n"<<queue[front]<<" deleted";
|
||||
front=(front+1)%10;
|
||||
count--;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
void show()
|
||||
{
|
||||
for (int i = 0; i<count; i++)
|
||||
{
|
||||
cout<<queue[(i+front)%10]<<"\t";
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int ch, x;
|
||||
do
|
||||
{
|
||||
cout<<"\n1. Enque";
|
||||
cout<<"\n2. Deque";
|
||||
cout<<"\n3. Print";
|
||||
cout<<"\nEnter Your Choice : ";
|
||||
cin>>ch;
|
||||
if (ch==1)
|
||||
{
|
||||
cout<<"\nInsert : ";
|
||||
cin>>x;
|
||||
Enque(x);
|
||||
}
|
||||
else if (ch==2)
|
||||
{
|
||||
Deque();
|
||||
}
|
||||
else if (ch==3)
|
||||
{
|
||||
show();
|
||||
}
|
||||
}
|
||||
while(ch!=0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,30 +0,0 @@
|
||||
#include <iostream>
|
||||
int main()
|
||||
{
|
||||
int i,j,m,n;
|
||||
cout <<"Enter size of array 1:";
|
||||
cin >> m;
|
||||
cout <<"Enter size of array 2:";
|
||||
cin >> n;
|
||||
int a[m];
|
||||
int b[n];
|
||||
cout <<"Enter elements of array 1:";
|
||||
for(i=0;i<m;i++)
|
||||
cin >> a[i];
|
||||
for(i=0;i<n;i++)
|
||||
cin >> b[i];
|
||||
i=0;j=0;
|
||||
while((i<m)&&(j<n))
|
||||
{
|
||||
if(a[i]<b[j])
|
||||
i++;
|
||||
else if(a[i]>b[j])
|
||||
j++;
|
||||
else
|
||||
{
|
||||
cout << a[i++]<<" ";
|
||||
j++;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#include <iostream>
|
||||
int main()
|
||||
{
|
||||
int m,n,i=0,j=0;
|
||||
cout << "Enter size of both arrays:";
|
||||
cin >> m >> n;
|
||||
int a[m];
|
||||
int b[n];
|
||||
cout << "Enter elements of array 1:";
|
||||
for(i=0;i<m;i++)
|
||||
cin >>a[i];
|
||||
cout << "Enter elements of array 2:";
|
||||
for(i=0;i<n;i++)
|
||||
cin >> b[i];
|
||||
i=0;j=0;
|
||||
while((i<m)&&(j<n))
|
||||
{
|
||||
if(a[i]<b[j])
|
||||
cout << a[i++] <<" ";
|
||||
else if(a[i]>b[j])
|
||||
cout << b[j++] <<" ";
|
||||
else
|
||||
{
|
||||
cout << a[i++];
|
||||
j++;
|
||||
}
|
||||
}
|
||||
while(i<m)
|
||||
cout<< a[i++] <<" ";
|
||||
while(j<n)
|
||||
cout<< b[j++]<<" ";
|
||||
return 0;
|
||||
}
|
||||
@@ -1,162 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
//node defined
|
||||
class node
|
||||
{
|
||||
public:
|
||||
int data;
|
||||
node* link;
|
||||
node(int d)
|
||||
{
|
||||
data = d;
|
||||
link = NULL;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
//printing the linked list
|
||||
void print(node* head)
|
||||
{
|
||||
node* current = head;
|
||||
while (current != NULL)
|
||||
{
|
||||
cout << current->data << " ";
|
||||
current = current-> link;
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
|
||||
//creating the linked list with 'n' nodes
|
||||
node* createlist(int n)
|
||||
{
|
||||
node* head = NULL;
|
||||
node* t = NULL;
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
node* temp = NULL;
|
||||
int num;
|
||||
cin >> num;
|
||||
temp = new node(num);
|
||||
if (head == NULL)
|
||||
{
|
||||
head = temp;
|
||||
t = temp;
|
||||
continue;
|
||||
}
|
||||
if (t->link == NULL) t->link = temp;
|
||||
t = temp;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
|
||||
//performing selection sort on the linked list in an iterative manner
|
||||
void my_selection_sort_linked_list(node* &head)
|
||||
{
|
||||
node* min = head; //throughout the algorithm 'min' is used to denote the node with min value out of all the nodes left for scanning
|
||||
//while scanning if we find a node 'X' with value lesser than min,
|
||||
//then we update the pointers in such a way that 'X' becomes the predecessor of 'min'
|
||||
node* current = min->link; // 'current' refers to the current node we are scanning
|
||||
node* previous = min; //'previous' refers to the node that is previous to the current node
|
||||
node* temp = NULL; // 'temp' in this algo is used to point to the last node of the sorted part of the linked list.
|
||||
//eg. If at any time instance the state of the linked list is suppose 1->2->5->3->8->NULL
|
||||
//then, we see that "1->2" is the sorted part of the LL, and therefore temp will be pointing to the last node of the sorted part,i.e,'2'
|
||||
//We keep on arranging the Linked list in such a way that after each iteration the node with 'min' value is placed at its correct position.
|
||||
//Eg. Let suppose initially we have 5->4->1->3->2->NULL
|
||||
//After 1st iteration : 1->4->5->3->2->NULL and so on
|
||||
|
||||
while (min->link != NULL) //so that all the nodes are scanned or until there exists a node
|
||||
{
|
||||
//pick the first node from the unsorted part and assume that it is the minimum and then start scanning from the next node
|
||||
|
||||
while (current != NULL) //suppose you choose the min node to be X, then scan starts from the (X+1)th node until its NULL. current = (X+1)th node and min = X
|
||||
{
|
||||
if (current->data < min->data) //if the current node is smaller than the presumed node 'min'
|
||||
{
|
||||
if (temp == NULL) //temp stays null for the first iteration, therefore it symbolizes that we are scanning for the first time
|
||||
{
|
||||
if (previous == min) //if the 'previous' is pointing to the 'min' node
|
||||
{
|
||||
//Update the pointers
|
||||
head = current; //update the head pointer with the current node
|
||||
min->link = current->link;
|
||||
current->link = previous;
|
||||
min = current;
|
||||
current = previous->link;
|
||||
}
|
||||
else //if the 'previous' is not pointing to the 'min' node
|
||||
{
|
||||
//Update the pointers
|
||||
head = current; //update the head pointer with the current node
|
||||
previous->link = current->link;
|
||||
current->link = min;
|
||||
min = current;
|
||||
current = previous->link;
|
||||
}
|
||||
}
|
||||
else //if 'temp' is not NULL, i.e., its not the 1st iteration
|
||||
{
|
||||
temp->link = current;
|
||||
previous->link = current->link;
|
||||
current->link = min;
|
||||
min = current;
|
||||
current = previous->link;
|
||||
}
|
||||
}
|
||||
else //if the current node is greater than min, just move the previous and the current pointer a step further
|
||||
{
|
||||
previous = previous->link;
|
||||
current = current->link;
|
||||
}
|
||||
}
|
||||
|
||||
//update the pointers. Set 'temp' to the last node in the sorted part. Make 'min' move a step further so that 'min' points to the 1st node of the unsorted part
|
||||
//start the iteration again
|
||||
temp = min;
|
||||
min = min->link;
|
||||
previous = min;
|
||||
current = min->link;
|
||||
}
|
||||
}
|
||||
|
||||
// Test cases:
|
||||
|
||||
// enter the no. of nodes : 5
|
||||
// 8 9 3 1 4
|
||||
// original list is : 8 9 3 1 4
|
||||
// sorted list is : 1 3 4 8 9
|
||||
|
||||
// enter the no. of nodes : 3
|
||||
// -1 -2 -3
|
||||
// original list is : -1 -2 -3
|
||||
// sorted list is : -3 -2 -1
|
||||
|
||||
|
||||
// enter the no. of nodes : 8
|
||||
// 8 7 6 5 4 3 2 1
|
||||
// original list is : 8 7 6 5 4 3 2 1
|
||||
// sorted list is : 1 2 3 4 5 6 7 8
|
||||
|
||||
// enter the no. of nodes : 6
|
||||
// 5 3 4 1 -2 -4
|
||||
// original list is : 5 3 4 1 -2 -4
|
||||
// sorted list is : -4 -2 1 3 4 5
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
node* head = NULL;
|
||||
int n;
|
||||
cout << "enter the no. of nodes : "; //taking input from user about the number of nodes in linked list
|
||||
cin >> n;
|
||||
if (n == 0) return 0;
|
||||
head = createlist(n); //creating the list
|
||||
cout << "original list is : ";
|
||||
print(head); //printing the original linked list
|
||||
my_selection_sort_linked_list(head); //applying selection sort
|
||||
cout << "sorted list is : ";
|
||||
print(head); //printing the sorted linked list
|
||||
return 0;
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
//A buzz number is a number that is either divisble by 7 or has last digit as 7.
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int main()
|
||||
{
|
||||
int n,t;
|
||||
cin >> t;
|
||||
while(t--)
|
||||
{
|
||||
cin >> n;
|
||||
if((n%7==0)||(n%10==7))
|
||||
cout << n << " is a buzz number" << endl;
|
||||
else
|
||||
cout << n << " is not a buzz number" << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
int main(void){
|
||||
int valueToConvert = 0; //Holds user input
|
||||
int hexArray[8]; //Contains hex values backwards
|
||||
int i = 0; //counter
|
||||
char HexValues[] = "0123456789ABCDEF";
|
||||
|
||||
cout << "Enter a Decimal Value" << endl; //Displays request to stdout
|
||||
cin >> valueToConvert; //Stores value into valueToConvert via user input
|
||||
|
||||
while (valueToConvert > 15){ //Dec to Hex Algorithm
|
||||
hexArray[i++] = valueToConvert % 16; //Gets remainder
|
||||
valueToConvert /= 16;
|
||||
}
|
||||
hexArray[i] = valueToConvert; //Gets last value
|
||||
|
||||
cout << "Hex Value: ";
|
||||
while (i >= 0)
|
||||
cout<<HexValues[hexArray[i--]];
|
||||
|
||||
cout << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
//This Programme Converts a given decimal number in the range [0,4000)
|
||||
//to both Lower case and Upper case Roman Numeral
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
//This functions fills a string with character c, n times and returns it
|
||||
string fill( char c, int n )
|
||||
{
|
||||
string s = "";
|
||||
while( n-- ) s += c;
|
||||
return s;
|
||||
}
|
||||
|
||||
//to convert to lowercase Roman Numeral
|
||||
// the function works recursively
|
||||
string tolowerRoman( int n )
|
||||
{
|
||||
if( n < 4 ) return fill( 'i', n );
|
||||
if( n < 6 ) return fill( 'i', 5 - n ) + "v";
|
||||
if( n < 9 ) return string( "v" ) + fill( 'i', n - 5 );
|
||||
if( n < 11 ) return fill( 'i', 10 - n ) + "x";
|
||||
if( n < 40 ) return fill( 'x', n / 10 ) + tolowerRoman( n % 10 );
|
||||
if( n < 60 ) return fill( 'x', 5 - n / 10 ) + 'l' + tolowerRoman( n % 10 );
|
||||
if( n < 90 ) return string( "l" ) + fill( 'x', n / 10 - 5 ) + tolowerRoman( n % 10 );
|
||||
if( n < 110 ) return fill( 'x', 10 - n / 10 ) + "c" + tolowerRoman( n % 10 );
|
||||
if( n < 400 ) return fill( 'c', n / 100 ) + tolowerRoman( n % 100 );
|
||||
if( n < 600 ) return fill( 'c', 5 - n / 100 ) + 'd' + tolowerRoman( n % 100 );
|
||||
if( n < 900 ) return string( "d" ) + fill( 'c', n / 100 - 5 ) + tolowerRoman( n % 100 );
|
||||
if( n < 1100 ) return fill( 'c', 10 - n / 100 ) + "m" + tolowerRoman( n % 100 );
|
||||
if( n < 4000 ) return fill( 'm', n / 1000 ) + tolowerRoman( n % 1000 );
|
||||
return "?";
|
||||
}
|
||||
|
||||
//to convert to uppercase Roman Numeral
|
||||
// the function works recursively
|
||||
string toupperRoman( int n )
|
||||
{
|
||||
if( n < 4 ) return fill( 'I', n );
|
||||
if( n < 6 ) return fill( 'I', 5 - n ) + "V";
|
||||
if( n < 9 ) return string( "V" ) + fill( 'I', n - 5 );
|
||||
if( n < 11 ) return fill( 'I', 10 - n ) + "X";
|
||||
if( n < 40 ) return fill( 'X', n / 10 ) + toupperRoman( n % 10 );
|
||||
if( n < 60 ) return fill( 'X', 5 - n / 10 ) + 'L' + toupperRoman( n % 10 );
|
||||
if( n < 90 ) return string( "L" ) + fill( 'X', n / 10 - 5 ) + toupperRoman( n % 10 );
|
||||
if( n < 110 ) return fill( 'X', 10 - n / 10 ) + "C" + toupperRoman( n % 10 );
|
||||
if( n < 400 ) return fill( 'C', n / 100 ) + toupperRoman( n % 100 );
|
||||
if( n < 600 ) return fill( 'C', 5 - n / 100 ) + 'D' + toupperRoman( n % 100 );
|
||||
if( n < 900 ) return string( "D" ) + fill( 'C', n / 100 - 5 ) + toupperRoman( n % 100 );
|
||||
if( n < 1100 ) return fill( 'C', 10 - n / 100 ) + "M" + toupperRoman( n % 100 );
|
||||
if( n < 4000 ) return fill( 'M', n / 1000 ) + toupperRoman( n % 1000 );
|
||||
return "?";
|
||||
}
|
||||
|
||||
//main function
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int n;
|
||||
cout << "\t\tRoman numbers converter\n\n";
|
||||
cout << "Type in decimal number between 0 up to 4000 (exclusive): ";
|
||||
cin >> n;
|
||||
cout << n << " in Upper Roman Numerals is " << toupperRoman(n) << "\n";
|
||||
cout << n << " in Lower Roman Numerals is " << tolowerRoman(n) << "\n";
|
||||
return 0;
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
//This program aims at calculating the GCD of n numbers by division method
|
||||
#include <iostream>
|
||||
using namepsace std;
|
||||
int main()
|
||||
{
|
||||
cout <<"Enter value of n:"<<endl;
|
||||
cin >> n;
|
||||
int a[n];
|
||||
int i,j,gcd;
|
||||
cout << "Enter the n numbers:" << endl;
|
||||
for(i=0;i<n;i++)
|
||||
cin >> a[i];
|
||||
j=1; //to access all elements of the array starting from 1
|
||||
gcd=a[0];
|
||||
while(j<n)
|
||||
{
|
||||
if(a[j]%gcd==0) //value of gcd is as needed so far
|
||||
j++; //so we check for next element
|
||||
else
|
||||
gcd=a[j]%gcd; //calculating GCD by division method
|
||||
}
|
||||
cout << "GCD of entered n numbers:" << gcd;
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
/* A happy number is a number whose sum of digits is calculated until the sum is a single digit,
|
||||
and this sum turns out to be 1 */
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int n,k,s=0,d;
|
||||
cout << "Enter a number:";
|
||||
cin >> n;
|
||||
s=0;k=n;
|
||||
while(k>9)
|
||||
{
|
||||
while(k!=0)
|
||||
{
|
||||
d=k%10;
|
||||
s+=d;
|
||||
k/=10;
|
||||
}
|
||||
k=s;
|
||||
s=0;
|
||||
}
|
||||
if(k==1)
|
||||
cout << n << " is a happy number" << endl;
|
||||
else
|
||||
cout << n << " is not a happy number" << endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
#include<iostream>
|
||||
#include<string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
#define MAX 100
|
||||
|
||||
// -------------- stack --------------
|
||||
|
||||
char stack[MAX];
|
||||
int top = -1;
|
||||
|
||||
void push(char ch){
|
||||
stack[ ++top ] = ch;
|
||||
}
|
||||
|
||||
char pop(){
|
||||
return stack[ top-- ];
|
||||
}
|
||||
|
||||
// -------------- end stack -----------
|
||||
|
||||
char opening(char ch){
|
||||
switch(ch){
|
||||
case '}':
|
||||
return '{';
|
||||
case ']':
|
||||
return '[';
|
||||
case ')':
|
||||
return '(';
|
||||
case '>':
|
||||
return '<';
|
||||
}
|
||||
}
|
||||
|
||||
int main(){
|
||||
|
||||
string exp;
|
||||
int valid = 1, i = 0;
|
||||
cout<<"Enter The Expression : ";
|
||||
cin >> exp;
|
||||
|
||||
while (valid == 1 && i < exp.length()){
|
||||
if (exp[i] == '(' || exp[i] == '{' || exp[i] == '[' || exp[i] == '<'){
|
||||
push(exp[i]);
|
||||
}
|
||||
else if (top >= 0 && stack[top] == opening(exp[i])){
|
||||
pop();
|
||||
}
|
||||
else{
|
||||
valid = 0;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
|
||||
// makes sure the stack is empty after processsing (above)
|
||||
if (valid == 1 && top == -1){
|
||||
cout<<"\nCorrect Expression";
|
||||
}
|
||||
else{
|
||||
cout<<"\nWrong Expression";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
|
||||
//A simple and efficient implementation of a function to test if a number is prime, based on the fact that
|
||||
//Every Prime number, except 2 and 3 are of the form 6*k+1 or 6*k-1 for integer values of k.
|
||||
|
||||
bool IsPrime( int number )
|
||||
{
|
||||
if ( ( (!(number & 1)) && number != 2 ) || (number < 2) || (number % 3 == 0 && number != 3) )
|
||||
return false;
|
||||
|
||||
for( int k = 1; 36*k*k-12*k < number;++k)
|
||||
{
|
||||
if ( (number % (6*k+1) == 0) || (number % (6*k-1) == 0) )
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
//Main Function
|
||||
cout <<"Enter the value of n to check if Prime\n";
|
||||
int n;
|
||||
cin >> n;
|
||||
if(IsPrime(n))
|
||||
cout << n << " is Prime" <<endl;
|
||||
else
|
||||
cout << n << " is not Prime" <<endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
Multiply(int A[][], int B[][], int n)
|
||||
{
|
||||
if (n==2)
|
||||
{
|
||||
int p1= (a[0][0] + a[1][1])*(b[0][0]+b[1][1]);
|
||||
int p2= (a[1][0]+a[1][1])*b[0][0];
|
||||
int p3= a[0][0]*(b[0][1]-b[1][1]);
|
||||
int p4= a[1][1]*(b[1][0]-b[0][0]);
|
||||
int p5= (a[0][0]+a[0][1])*b[1][1];
|
||||
int p6= (a[1][0]-a[0][0])*(b[0][0]+b[0][1]);
|
||||
int p7= (a[0][1]-a[1][1])*(b[1][0]+b[1][1]);
|
||||
|
||||
|
||||
int c[n][n];
|
||||
c[0][0]=p1+p4-p5+p7;
|
||||
c[0][1]=p3+p5;
|
||||
c[1][0]=p2+p4;
|
||||
c[1][1]=p1-p2+p3+p6;
|
||||
|
||||
return c[][];
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int p,q,r,s;
|
||||
cout<<"Enter the dimensions of Matrices";
|
||||
cin>>n;
|
||||
int A[n][n],;
|
||||
int B[n][n],;
|
||||
cout<<"Enter the elements of Matrix A";
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
for (int j = 0; j <n ; j++)
|
||||
{
|
||||
cin>>A[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
cout<<"Enter the elements of Matrix B";
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
for (int j = 0; j <n ; j++)
|
||||
{
|
||||
cin>>B[i][j];
|
||||
}
|
||||
}
|
||||
|
||||
Multiply(A, B, n);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
struct tower
|
||||
{
|
||||
int values[10];
|
||||
int top;
|
||||
}F, U, T;
|
||||
|
||||
|
||||
|
||||
void show()
|
||||
{
|
||||
cout<<"\n\n\tF : ";
|
||||
for(int i=0; i<F.top; i++)
|
||||
{
|
||||
cout<<F.values[i]<<"\t";
|
||||
}
|
||||
cout<<"\n\tU : ";
|
||||
for(int i=0; i<U.top; i++)
|
||||
{
|
||||
cout<<U.values[i]<<"\t";
|
||||
}
|
||||
cout<<"\n\tT : ";
|
||||
for(int i=0; i<T.top; i++)
|
||||
{
|
||||
cout<<T.values[i]<<"\t";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void mov(tower &From, tower &To)
|
||||
{
|
||||
--From.top;
|
||||
To.values[To.top]=From.values[From.top];
|
||||
++To.top;
|
||||
}
|
||||
|
||||
void TH(int n, tower &From, tower &Using, tower &To)
|
||||
{
|
||||
|
||||
if (n==1)
|
||||
{
|
||||
mov(From, To);
|
||||
show();
|
||||
|
||||
}
|
||||
else
|
||||
{
|
||||
TH(n-1, From, To, Using);
|
||||
mov(From, To);
|
||||
show();
|
||||
TH(n-1, Using, From, To);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
F.top=0;
|
||||
U.top=0;
|
||||
T.top=0;
|
||||
|
||||
int no;
|
||||
|
||||
cout << "\nEnter number of discs : " ;
|
||||
cin >> no;
|
||||
|
||||
for (int i = no; i >0; i--)
|
||||
{
|
||||
F.values[F.top++]=i;
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
show();
|
||||
TH(no, F, U, T);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
void genArray(int a[][10],int r,int c){
|
||||
|
||||
int value=1;
|
||||
for(int i=0;i<r;i++){
|
||||
for(int j=0;j<c;j++){
|
||||
a[i][j] = value;
|
||||
cout<<a[i][j]<<" ";
|
||||
value++;
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
}
|
||||
void spiralPrint(int a[][10],int r,int c){
|
||||
|
||||
int startRow=0,endRow=r-1;
|
||||
int startCol =0, endCol = c-1;
|
||||
int cnt=0;
|
||||
|
||||
while(startRow<=endRow && startCol<=endCol){
|
||||
|
||||
///Print start row
|
||||
for(int i=startCol;i<=endCol;i++,cnt++){
|
||||
cout<<a[startRow][i]<<" ";
|
||||
}
|
||||
startRow++;
|
||||
|
||||
///Print the end col
|
||||
for(int i=startRow;i<=endRow;i++,cnt++){
|
||||
cout<<a[i][endCol]<<" ";
|
||||
}
|
||||
endCol--;
|
||||
|
||||
///Print the end row
|
||||
if(cnt==r*c){
|
||||
break;
|
||||
}
|
||||
|
||||
for(int i=endCol;i>=startCol;i--,cnt++){
|
||||
cout<<a[endRow][i]<<" ";
|
||||
}
|
||||
endRow--;
|
||||
|
||||
///Print the start Col
|
||||
if(cnt==r*c){
|
||||
break;
|
||||
}
|
||||
for(int i=endRow;i>=startRow;i--,cnt++){
|
||||
cout<<a[i][startCol]<<" ";
|
||||
}
|
||||
startCol++;
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int a[10][10];
|
||||
|
||||
int r,c;
|
||||
cin>>r>>c;
|
||||
genArray(a,r,c);
|
||||
spiralPrint(a,r,c);
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
21
README.md
21
README.md
@@ -1,15 +1,10 @@
|
||||
# C++
|
||||
# The Algorithms - C++
|
||||
[](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md)
|
||||

|
||||

|
||||
|
||||
This repository contains some useful algorithms and data structures.
|
||||
### All algorithms implemented in C++ (for education)
|
||||
The implementations are for learning purpose. They may be less efficient than the implementation in the standard library.
|
||||
|
||||
### Contribute
|
||||
|
||||
How you can contribute? See this small guide.
|
||||
|
||||
* Use the directory structure of the repository.
|
||||
* Please describe your pull requests.
|
||||
* Don't use **bits/stdc++.h** because this is quite Linux specific and slows down the compiler process.
|
||||
* Put comments in your code.
|
||||
* Avoid **struct**. Instead use the **class** keyword.
|
||||
* Add some test cases in the main-function.
|
||||
* Can suggest any change in present algorithms(if needed).
|
||||
### Contribute Guidelines
|
||||
Read our [Contribution Guidelines](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTION.md) before you contribute.
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
#include "bits/stdc++.h"
|
||||
using namespace std;
|
||||
const int N = 1e6+5;
|
||||
int a[N],bucket[N],cnt[N];
|
||||
int bucket_size;
|
||||
struct query{
|
||||
int l,r,i;
|
||||
}q[N];
|
||||
int ans=0;
|
||||
|
||||
void add(int index)
|
||||
{
|
||||
cnt[a[index]]++;
|
||||
if(cnt[a[index]] == 1)
|
||||
ans++;
|
||||
}
|
||||
void remove(int index)
|
||||
{
|
||||
cnt[a[index]]--;
|
||||
if(cnt[a[index]] == 0)
|
||||
ans--;
|
||||
}
|
||||
|
||||
|
||||
bool mycmp(query x, query y)
|
||||
{
|
||||
if(x.l/bucket_size != y.l/bucket_size)
|
||||
return x.l/bucket_size < y.l/bucket_size;
|
||||
return x.r<y.r;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int n,t,i,j,k=0;
|
||||
scanf("%d",&n);
|
||||
for(i=0;i<n;i++)
|
||||
scanf("%d",&a[i]);
|
||||
bucket_size = ceil(sqrt(n));
|
||||
scanf("%d",&t);
|
||||
for(i=0;i<t;i++)
|
||||
{
|
||||
scanf("%d %d",&q[i].l,&q[i].r);
|
||||
q[i].l--; q[i].r--;
|
||||
q[i].i = i;
|
||||
}
|
||||
sort(q,q+t,mycmp);
|
||||
int left=0,right=0;
|
||||
for(i=0;i<t;i++)
|
||||
{
|
||||
int L=q[i].l, R=q[i].r;
|
||||
while(left < L)
|
||||
{
|
||||
remove(left);
|
||||
left++;
|
||||
}
|
||||
while(left>L)
|
||||
{
|
||||
add(left-1);
|
||||
left--;
|
||||
}
|
||||
while(right<=R)
|
||||
{
|
||||
add(right);
|
||||
right++;
|
||||
}
|
||||
while(right>R+1)
|
||||
{
|
||||
remove(right-1);
|
||||
right--;
|
||||
}
|
||||
bucket[q[i].i] = ans;
|
||||
}
|
||||
for(i=0;i<t;i++)
|
||||
printf("%d\n",bucket[i]);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,90 +0,0 @@
|
||||
#include <bits/stdc++.h>
|
||||
#define MAX 4000000
|
||||
using namespace std;
|
||||
typedef long long ll;
|
||||
void ConsTree(ll arr[],ll segtree[],ll low,ll high,ll pos)
|
||||
{
|
||||
if(low == high)
|
||||
{
|
||||
segtree[pos] = arr[low];
|
||||
return;
|
||||
}
|
||||
ll mid = (low+high)/2;
|
||||
ConsTree(arr,segtree,low,mid,2*pos+1);
|
||||
ConsTree(arr,segtree,mid+1,high,2*pos+2);
|
||||
segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2];
|
||||
}
|
||||
ll query(ll segtree[],ll lazy[],ll qlow,ll qhigh,ll low,ll high,ll pos)
|
||||
{
|
||||
if(low > high)
|
||||
return 0;
|
||||
if(qlow>high || qhigh<low)
|
||||
return 0;
|
||||
if(lazy[pos] != 0)
|
||||
{
|
||||
segtree[pos] += lazy[pos]*(high-low+1);
|
||||
if(low != high)
|
||||
{
|
||||
lazy[2*pos+1] += lazy[pos];
|
||||
lazy[2*pos+2] += lazy[pos];
|
||||
}
|
||||
lazy[pos] = 0;
|
||||
}
|
||||
if(qlow<=low && qhigh>=high)
|
||||
return segtree[pos];
|
||||
ll mid = (low+high)/2;
|
||||
return query(segtree,lazy,qlow,qhigh,low,mid,2*pos+1) + query(segtree,lazy,qlow,qhigh,mid+1,high,2*pos+2);
|
||||
}
|
||||
void update(ll segtree[],ll lazy[],ll start,ll end,ll delta,ll low,ll high,ll pos)
|
||||
{
|
||||
if(low>high)
|
||||
return;
|
||||
if(lazy[pos] != 0)
|
||||
{
|
||||
segtree[pos] += lazy[pos]*(high-low+1);
|
||||
if(low!=high)
|
||||
{
|
||||
lazy[2*pos+1] += lazy[pos];
|
||||
lazy[2*pos+2] += lazy[pos];
|
||||
}
|
||||
lazy[pos] = 0;
|
||||
}
|
||||
if(start > high || end < low)
|
||||
return;
|
||||
if(start <= low && end >= high)
|
||||
{
|
||||
segtree[pos] += delta*(high-low+1);
|
||||
if(low != high)
|
||||
{
|
||||
lazy[2*pos+1] += delta;
|
||||
lazy[2*pos+2] += delta;
|
||||
}
|
||||
return;
|
||||
}
|
||||
ll mid = (low+high)/2;
|
||||
update(segtree,lazy,start,end,delta,low,mid,2*pos+1);
|
||||
update(segtree,lazy,start,end,delta,mid+1,high,2*pos+2);
|
||||
segtree[pos] = segtree[2*pos+1] + segtree[2*pos+2];
|
||||
}
|
||||
int main() {
|
||||
ll n,c;
|
||||
scanf("%lld %lld",&n,&c);
|
||||
ll arr[n]={0},p,q,v,choice;
|
||||
ll segtree[MAX],lazy[MAX]={0};
|
||||
ConsTree(arr,segtree,0,n-1,0);
|
||||
while(c--)
|
||||
{
|
||||
scanf("%lld",&choice);
|
||||
if(choice == 0)
|
||||
{
|
||||
scanf("%lld %lld %lld",&p,&q,&v);
|
||||
update(segtree,lazy,p-1,q-1,v,0,n-1,0);
|
||||
}
|
||||
else
|
||||
{
|
||||
scanf("%lld %lld",&p,&q);
|
||||
printf("%lld\n",query(segtree,lazy,p-1,q-1,0,n-1,0));
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
int binary_search(int a[],int l,int r,int key){
|
||||
while(l<=r){
|
||||
int m = l+(r-l)/2;
|
||||
if(key==a[m])
|
||||
return m;
|
||||
else if(key<a[m])
|
||||
r = m-1;
|
||||
else
|
||||
l = m+1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int n,key;
|
||||
cout<<"Enter size of array: ";
|
||||
cin>>n;
|
||||
cout<<"Enter array elements: ";
|
||||
int a[n];
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
cin>>a[i];
|
||||
}
|
||||
cout<<"Enter search key: ";
|
||||
cin>>key;
|
||||
int res = binary_search(a,0,n-1,key);
|
||||
if(res != -1)
|
||||
cout<<key<<" found at index "<<res<<endl;
|
||||
else
|
||||
cout<<key<<" not found"<<endl;
|
||||
return 0;
|
||||
}
|
||||
@@ -1,48 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int LinearSearch(int *array, int size, int key)
|
||||
{
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
if (array[i]==key)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
int size;
|
||||
cout<<"\nEnter the size of the Array : ";
|
||||
cin >> size;
|
||||
|
||||
int array[size];
|
||||
int key;
|
||||
|
||||
//Input array
|
||||
cout<<"\nEnter the Array of " << size << " numbers : ";
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
cin>>array[i];
|
||||
}
|
||||
|
||||
cout<<"\nEnter the number to be searched : ";
|
||||
cin>>key;
|
||||
|
||||
int index=LinearSearch(array, size, key);
|
||||
if (index!=-1)
|
||||
{
|
||||
cout<<"\nNumber found at index : "<<index;
|
||||
}
|
||||
else
|
||||
{
|
||||
cout<<"\nNot found";
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <cstdlib>
|
||||
|
||||
using namespace std;
|
||||
char paragraph;
|
||||
|
||||
int main()
|
||||
{
|
||||
string paragraph;
|
||||
cout << "Please enter your paragraph: \n";
|
||||
getline (cin,paragraph);
|
||||
cout << "\nHello, your paragraph is:\n " << paragraph << "!\n";
|
||||
cout << "\nThe size of your paragraph = " << paragraph.size() << " characters. \n\n";
|
||||
|
||||
if (paragraph.empty())
|
||||
{
|
||||
cout << "\nThe paragraph is empty" << endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
while (true) {
|
||||
string word;
|
||||
cout << "Please enter the word you are searching for: ";
|
||||
getline (cin,word);
|
||||
cout << "Hello, your word is " << word << "!\n";
|
||||
if (paragraph.find(word) == string::npos)
|
||||
{
|
||||
cout << word << " does not exist in the sentence" << endl;
|
||||
}
|
||||
else
|
||||
{
|
||||
cout << "The word " << word << " is now found at location " << paragraph.find(word) << endl << endl;
|
||||
}
|
||||
system("pause");
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
/*
|
||||
* This is a divide and conquer algorithm.
|
||||
* It does this by dividing the search space by 3 parts and
|
||||
* using its property (usually monotonic property) to find
|
||||
* the desired index.
|
||||
*
|
||||
* Time Complexity : O(log3 n)
|
||||
* Space Complexity : O(1) (without the array)
|
||||
*/
|
||||
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
/*
|
||||
* The absolutePrecision can be modified to fit preference but
|
||||
* it is recommended to not go lower than 10 due to errors that
|
||||
* may occur.
|
||||
*
|
||||
* The value of _target should be decided or can be decided later
|
||||
* by using the variable of the function.
|
||||
*/
|
||||
|
||||
#define _target 10
|
||||
#define absolutePrecision 10
|
||||
#define MAX 10000000
|
||||
|
||||
int N = 21;
|
||||
int A[MAX] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,3,4,10};
|
||||
|
||||
/*
|
||||
* get_input function is to receive input from standard IO
|
||||
*/
|
||||
void get_input()
|
||||
{
|
||||
// TODO: Get input from STDIO or write input to memory as done above.
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
* This is the iterative method of the ternary search which returns the index of the element.
|
||||
*/
|
||||
int it_ternary_search(int left, int right, int A[],int target)
|
||||
{
|
||||
while (1)
|
||||
{
|
||||
if(left<right)
|
||||
{
|
||||
if(right-left < absolutePrecision)
|
||||
{
|
||||
for(int i=left;i<=right;i++)
|
||||
if(A[i] == target) return i;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int oneThird = (left+right)/3+1;
|
||||
int twoThird = (left+right)*2/3+1;
|
||||
|
||||
if(A[oneThird] == target) return oneThird;
|
||||
else if(A[twoThird] == target) return twoThird;
|
||||
|
||||
else if(target > A[twoThird]) left = twoThird+1;
|
||||
else if(target < A[oneThird]) right = oneThird-1;
|
||||
|
||||
else left = oneThird+1, right = twoThird-1;
|
||||
}
|
||||
else return -1;
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* This is the recursive method of the ternary search which returns the index of the element.
|
||||
*/
|
||||
int rec_ternary_search(int left, int right, int A[],int target)
|
||||
{
|
||||
if(left<right)
|
||||
{
|
||||
if(right-left < absolutePrecision)
|
||||
{
|
||||
for(int i=left;i<=right;i++)
|
||||
if(A[i] == target) return i;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
int oneThird = (left+right)/3+1;
|
||||
int twoThird = (left+right)*2/3+1;
|
||||
|
||||
if(A[oneThird] == target) return oneThird;
|
||||
if(A[twoThird] == target) return twoThird;
|
||||
|
||||
if(target < A[oneThird]) return rec_ternary_search(left, oneThird-1, A, target);
|
||||
if(target > A[twoThird]) return rec_ternary_search(twoThird+1, right, A, target);
|
||||
|
||||
return rec_ternary_search(oneThird+1, twoThird-1, A, target);
|
||||
}
|
||||
else return -1;
|
||||
}
|
||||
|
||||
/*
|
||||
* ternary_search is a template function
|
||||
* You could either use it_ternary_search or rec_ternary_search according to preference.
|
||||
*/
|
||||
void ternary_search(int N,int A[],int target)
|
||||
{
|
||||
cout << it_ternary_search(0,N-1,A,target) << '\t';
|
||||
cout << rec_ternary_search(0,N-1,A,target) << '\t';
|
||||
cout << '\n';
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
get_input();
|
||||
ternary_search(N,A,_target);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,76 +0,0 @@
|
||||
// Source : https://www.geeksforgeeks.org/bitonic-sort/
|
||||
|
||||
/* C++ Program for Bitonic Sort. Note that this program
|
||||
works only when size of input is a power of 2. */
|
||||
|
||||
#include<stdio.h>
|
||||
#include<algorithm.h>
|
||||
using namespace std;
|
||||
|
||||
/*The parameter dir indicates the sorting direction, ASCENDING
|
||||
or DESCENDING; if (a[i] > a[j]) agrees with the direction,
|
||||
then a[i] and a[j] are interchanged.*/
|
||||
void compAndSwap(int a[], int i, int j, int dir)
|
||||
{
|
||||
if (dir==(a[i]>a[j]))
|
||||
swap(a[i],a[j]);
|
||||
}
|
||||
|
||||
/*It recursively sorts a bitonic sequence in ascending order,
|
||||
if dir = 1, and in descending order otherwise (means dir=0).
|
||||
The sequence to be sorted starts at index position low,
|
||||
the parameter cnt is the number of elements to be sorted.*/
|
||||
void bitonicMerge(int a[], int low, int cnt, int dir)
|
||||
{
|
||||
if (cnt>1)
|
||||
{
|
||||
int k = cnt/2;
|
||||
for (int i=low; i<low+k; i++)
|
||||
compAndSwap(a, i, i+k, dir);
|
||||
bitonicMerge(a, low, k, dir);
|
||||
bitonicMerge(a, low+k, k, dir);
|
||||
}
|
||||
}
|
||||
|
||||
/* This function first produces a bitonic sequence by recursively
|
||||
sorting its two halves in opposite sorting orders, and then
|
||||
calls bitonicMerge to make them in the same order */
|
||||
void bitonicSort(int a[],int low, int cnt, int dir)
|
||||
{
|
||||
if (cnt>1)
|
||||
{
|
||||
int k = cnt/2;
|
||||
|
||||
// sort in ascending order since dir here is 1
|
||||
bitonicSort(a, low, k, 1);
|
||||
|
||||
// sort in descending order since dir here is 0
|
||||
bitonicSort(a, low+k, k, 0);
|
||||
|
||||
// Will merge wole sequence in ascending order
|
||||
// since dir=1.
|
||||
bitonicMerge(a,low, cnt, dir);
|
||||
}
|
||||
}
|
||||
|
||||
/* Caller of bitonicSort for sorting the entire array of
|
||||
length N in ASCENDING order */
|
||||
void sort(int a[], int N, int up)
|
||||
{
|
||||
bitonicSort(a,0, N, up);
|
||||
}
|
||||
|
||||
// Driver code
|
||||
int main()
|
||||
{
|
||||
int a[]= {3, 7, 4, 8, 6, 2, 1, 5};
|
||||
int N = sizeof(a)/sizeof(a[0]);
|
||||
|
||||
int up = 1; // means sort in ascending order
|
||||
sort(a, N, up);
|
||||
|
||||
printf("Sorted array: \n");
|
||||
for (int i=0; i<N; i++)
|
||||
printf("%d ", a[i]);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,116 +0,0 @@
|
||||
//Returns Sorted elements after performing Cocktail Selection Sort
|
||||
//It is a Sorting algorithm which chooses the minimum and maximum element in an array simultaneously,
|
||||
//and swaps it with the lowest and highest available position iteratively or recursively
|
||||
|
||||
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
//Iterative Version
|
||||
|
||||
void CocktailSelectionSort(vector <int> &vec,int low,int high)
|
||||
{
|
||||
while(low<=high)
|
||||
{
|
||||
int minimum=vec[low];
|
||||
int minimumindex=low;
|
||||
int maximum=vec[high];
|
||||
int maximumindex=high;
|
||||
|
||||
for(int i=low;i<=high;i++)
|
||||
{
|
||||
if(vec[i]>=maximum)
|
||||
{
|
||||
maximum=vec[i];
|
||||
maximumindex=i;
|
||||
}
|
||||
if(vec[i]<=minimum)
|
||||
{
|
||||
minimum=vec[i];
|
||||
minimumindex=i;
|
||||
}
|
||||
}
|
||||
if(low!=maximumindex||high!=minimumindex)
|
||||
{
|
||||
swap(vec[low],vec[minimumindex]);
|
||||
swap(vec[high],vec[maximumindex]);
|
||||
}
|
||||
else
|
||||
{
|
||||
swap(vec[low],vec[high]);
|
||||
}
|
||||
|
||||
low++;
|
||||
high--;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
//Recursive Version
|
||||
|
||||
void CocktailSelectionSort(vector <int> &vec,int low,int high)
|
||||
{
|
||||
|
||||
if(low>=high)
|
||||
return;
|
||||
|
||||
int minimum=vec[low];
|
||||
int minimumindex=low;
|
||||
int maximum=vec[high];
|
||||
int maximumindex=high;
|
||||
|
||||
for(int i=low;i<=high;i++)
|
||||
{
|
||||
if(vec[i]>=maximum)
|
||||
{
|
||||
maximum=vec[i];
|
||||
maximumindex=i;
|
||||
}
|
||||
if(vec[i]<=minimum)
|
||||
{
|
||||
minimum=vec[i];
|
||||
minimumindex=i;
|
||||
}
|
||||
}
|
||||
if(low!=maximumindex||high!=minimumindex)
|
||||
{
|
||||
swap(vec[low],vec[minimumindex]);
|
||||
swap(vec[high],vec[maximumindex]);
|
||||
}
|
||||
else
|
||||
{
|
||||
swap(vec[low],vec[high]);
|
||||
}
|
||||
|
||||
CocktailSelectionSort(vec,low+1,high-1);
|
||||
|
||||
|
||||
}
|
||||
|
||||
|
||||
//main function, select any one of iterative or recursive version
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int n;
|
||||
cout << "Enter number of elements\n";
|
||||
cin >> n;
|
||||
std::vector<int> v(n);
|
||||
cout << "Enter all the elements\n";
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
cin >> v[i];
|
||||
}
|
||||
|
||||
CocktailSelectionSort(v,0,n-1);
|
||||
cout << "Sorted elements are\n";
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
cout << v[i] << " ";
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
// C++ Program for counting sort
|
||||
#include <iostream>
|
||||
|
||||
using namespace std;
|
||||
|
||||
void countSort(string arr)
|
||||
{
|
||||
|
||||
string output;
|
||||
|
||||
int count[256], i;
|
||||
for(int i=0;i<256;i++)
|
||||
count[i]=0;
|
||||
|
||||
|
||||
for(i = 0; arr[i]; ++i)
|
||||
++count[arr[i]];
|
||||
|
||||
|
||||
for (i = 1; i <= 256; ++i)
|
||||
count[i] += count[i-1];
|
||||
|
||||
for (i = 0; arr[i]; ++i)
|
||||
{
|
||||
output[count[arr[i]]-1] = arr[i];
|
||||
--count[arr[i]];
|
||||
}
|
||||
|
||||
for (i = 0; arr[i]; ++i)
|
||||
arr[i] = output[i];
|
||||
|
||||
cout<<"Sorted character array is "<<arr;
|
||||
}
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
string arr;
|
||||
cin>>arr;
|
||||
|
||||
countSort(arr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int Max(int Arr[], int N){
|
||||
int max = Arr[0];
|
||||
for(int i=1; i<N; i++)
|
||||
if(Arr[i] > max)
|
||||
max = Arr[i];
|
||||
return max;
|
||||
}
|
||||
|
||||
int Min(int Arr[], int N){
|
||||
int min = Arr[0];
|
||||
for(int i=1; i<N; i++)
|
||||
if(Arr[i] < min)
|
||||
min = Arr[i];
|
||||
return min;
|
||||
}
|
||||
|
||||
void Print(int Arr[], int N){
|
||||
for(int i=0; i<N; i++) cout<<Arr[i] <<", ";
|
||||
}
|
||||
|
||||
int *Counting_Sort(int Arr[], int N){
|
||||
|
||||
int max = Max(Arr, N);
|
||||
int min = Min(Arr, N);
|
||||
int *Sorted_Arr = new int[N];
|
||||
|
||||
int *Count = new int[max-min+1];
|
||||
|
||||
for(int i=0; i<N; i++) Count[Arr[i]-min]++;
|
||||
|
||||
for(int i=1; i<(max-min+1); i++) Count[i]+=Count[i-1];
|
||||
|
||||
for(int i=N-1; i>=0; i--){
|
||||
Sorted_Arr[Count[Arr[i]-min]-1] = Arr[i];
|
||||
Count[Arr[i]-min]--;
|
||||
}
|
||||
|
||||
return Sorted_Arr;
|
||||
}
|
||||
|
||||
int main(){
|
||||
|
||||
int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22, 74, 25, 53, 15, 42, 36, 4, 69, 86, 19}, N = 20;
|
||||
int *Sorted_Arr;
|
||||
|
||||
cout<<"\n\tOrignal Array = ";Print(Arr, N);
|
||||
Sorted_Arr = Counting_Sort(Arr, N);
|
||||
cout<<"\n\t Sorted Array = ";Print(Sorted_Arr, N);
|
||||
cout<<endl;
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <conio.h>
|
||||
using namespace std;
|
||||
void max_heapify(int *a, int i, int n)
|
||||
{
|
||||
int j, temp;
|
||||
temp = a[i];
|
||||
j = 2 * i;
|
||||
while (j <= n)
|
||||
{
|
||||
if (j < n && a[j + 1] > a[j])
|
||||
j = j + 1;
|
||||
if (temp > a[j])
|
||||
break;
|
||||
else if (temp <= a[j])
|
||||
{
|
||||
a[j / 2] = a[j];
|
||||
j = 2 * j;
|
||||
}
|
||||
}
|
||||
a[j / 2] = temp;
|
||||
return;
|
||||
}
|
||||
void heapsort(int *a, int n)
|
||||
{
|
||||
int i, temp;
|
||||
for (i = n; i >= 2; i--)
|
||||
{
|
||||
temp = a[i];
|
||||
a[i] = a[1];
|
||||
a[1] = temp;
|
||||
max_heapify(a, 1, i - 1);
|
||||
}
|
||||
}
|
||||
void build_maxheap(int *a, int n)
|
||||
{
|
||||
int i;
|
||||
for (i = n / 2; i >= 1; i--)
|
||||
{
|
||||
max_heapify(a, i, n);
|
||||
}
|
||||
}
|
||||
int main()
|
||||
{
|
||||
int n, i, x;
|
||||
cout << "Enter number of elements of array\n";
|
||||
cin >> n;
|
||||
int a[20];
|
||||
for (i = 1; i <= n; i++)
|
||||
{
|
||||
cout << "Enter Element " << (i) << endl;
|
||||
cin >> a[i];
|
||||
}
|
||||
build_maxheap(a, n);
|
||||
heapsort(a, n);
|
||||
cout << "Sorted Output\n";
|
||||
for (i = 1; i <= n; i++)
|
||||
{
|
||||
cout << a[i] << endl;
|
||||
}
|
||||
getch();
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
//Insertion Sort
|
||||
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int n;
|
||||
cout<<"\nEnter the length of your array : ";
|
||||
cin>>n;
|
||||
int Array[n];
|
||||
cout<<"\nEnter any "<<n<<" Numbers for Unsorted Array : ";
|
||||
|
||||
//Input
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
cin>>Array[i];
|
||||
}
|
||||
|
||||
//Sorting
|
||||
for(int i=1; i<n; i++)
|
||||
{
|
||||
int temp=Array[i];
|
||||
int j=i-1;
|
||||
while(j>=0 && temp<Array[j])
|
||||
{
|
||||
Array[j+1]=Array[j];
|
||||
j--;
|
||||
}
|
||||
Array[j+1]=temp;
|
||||
}
|
||||
|
||||
//Output
|
||||
cout<<"\nSorted Array : ";
|
||||
for(int i=0; i<n; i++)
|
||||
{
|
||||
cout<<Array[i]<<"\t";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1,64 +0,0 @@
|
||||
//Using general algorithms to sort a collection of strings results in alphanumeric sort.
|
||||
//If it is a numeric string, it leads to unnatural sorting
|
||||
|
||||
//eg, an array of strings 1,10,100,2,20,200,3,30,300
|
||||
//would be sorted in that same order by using conventional sorting,
|
||||
//even though we know the correct sorting order is 1,2,3,10,20,30,100,200,300
|
||||
|
||||
//This Programme uses a comparator to sort the array in Numerical order instead of Alphanumeric order
|
||||
|
||||
|
||||
#include<iostream>
|
||||
#include<string>
|
||||
#include<algorithm>
|
||||
using namespace std;
|
||||
|
||||
bool NumericSort(string a,string b)
|
||||
{
|
||||
while(a[0]=='0')
|
||||
{
|
||||
a.erase(a.begin());
|
||||
}
|
||||
while(b[0]=='0')
|
||||
{
|
||||
b.erase(b.begin());
|
||||
}
|
||||
int n=a.length();
|
||||
int m=b.length();
|
||||
if(n==m)
|
||||
return a<b;
|
||||
return n<m;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int n;
|
||||
cout << "Enter number of elements to be sorted Numerically\n";
|
||||
cin >> n;
|
||||
|
||||
vector<string> v(n);
|
||||
cout << "Enter the string of Numbers\n";
|
||||
for(int i=0;i<n;i++)
|
||||
{
|
||||
cin >> v[i];
|
||||
}
|
||||
|
||||
sort(v.begin(),v.end());
|
||||
cout << "Elements sorted normally \n";
|
||||
for(int i=0;i<n;i++)
|
||||
{
|
||||
cout << v[i] << " ";
|
||||
}
|
||||
cout << "\n";
|
||||
|
||||
sort(v.begin(),v.end(),NumericSort);
|
||||
cout << "Elements sorted Numerically \n";
|
||||
for(int i=0;i<n;i++)
|
||||
{
|
||||
cout << v[i] << " ";
|
||||
}
|
||||
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
/* C implementation QuickSort */
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int partition (int arr[], int low, int high)
|
||||
{
|
||||
int pivot = arr[high]; // pivot
|
||||
int i = (low - 1); // Index of smaller element
|
||||
|
||||
for (int j = low; j <high; j++)
|
||||
{
|
||||
// If current element is smaller than or
|
||||
// equal to pivot
|
||||
if (arr[j] <= pivot)
|
||||
{
|
||||
i++; // increment index of smaller element
|
||||
int temp=arr[i];
|
||||
arr[i]=arr[j];
|
||||
arr[j]=temp;
|
||||
}
|
||||
}
|
||||
int temp=arr[i+1];
|
||||
arr[i+1]=arr[high];
|
||||
arr[high]=temp;
|
||||
return (i + 1);
|
||||
}
|
||||
|
||||
|
||||
void quickSort(int arr[], int low, int high)
|
||||
{
|
||||
if (low < high)
|
||||
{
|
||||
|
||||
int p= partition(arr, low, high);
|
||||
|
||||
quickSort(arr, low, p - 1);
|
||||
quickSort(arr, p + 1, high);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void show(int arr[], int size)
|
||||
{
|
||||
for (int i=0; i < size; i++)
|
||||
cout<<arr[i]<<"\n";
|
||||
}
|
||||
|
||||
// Driver program to test above functions
|
||||
int main()
|
||||
{
|
||||
int size;
|
||||
cout<<"\nEnter the number of elements : ";
|
||||
|
||||
cin>>size;
|
||||
|
||||
int arr[size];
|
||||
|
||||
cout<<"\nEnter the unsorted elements : ";
|
||||
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
cout<<"\n";
|
||||
cin>>arr[i];
|
||||
}
|
||||
quickSort(arr, 0, size);
|
||||
cout<<"Sorted array\n";
|
||||
show(arr, size);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,60 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <cstdlib>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
using namespace std;
|
||||
void radixsort(int a[],int n){
|
||||
int count[10];
|
||||
int output[n];
|
||||
memset(output,0,sizeof(output));
|
||||
memset(count,0,sizeof(count));
|
||||
int max = 0;
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
if (a[i]>max)
|
||||
{
|
||||
max = a[i];
|
||||
}
|
||||
}
|
||||
int maxdigits = 0;
|
||||
while(max){
|
||||
maxdigits++;
|
||||
max/=10;
|
||||
}
|
||||
for(int j=0;j<maxdigits;j++){
|
||||
for(int i=0;i<n;i++){
|
||||
int t = pow(10,j);
|
||||
count[(a[i]%(10*t))/t]++;
|
||||
}
|
||||
int k = 0;
|
||||
for(int p=0;p<10;p++){
|
||||
for(int i=0;i<n;i++){
|
||||
int t = pow(10,j);
|
||||
if((a[i]%(10*t))/t==p){
|
||||
output[k] = a[i];
|
||||
k++;
|
||||
}
|
||||
}
|
||||
}
|
||||
memset(count,0,sizeof(count));
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
a[i] = output[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
void print(int a[],int n){
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
cout<<a[i]<<" ";
|
||||
}
|
||||
cout<<endl;
|
||||
}
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int a[] = {170, 45, 75, 90, 802, 24, 2, 66};
|
||||
int n = sizeof(a)/sizeof(a[0]);
|
||||
radixsort(a,n);
|
||||
print(a,n);
|
||||
return 0;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
//Selection Sort
|
||||
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int Array[6];
|
||||
cout<<"\nEnter any 6 Numbers for Unsorted Array : ";
|
||||
|
||||
//Input
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
cin>>Array[i];
|
||||
}
|
||||
|
||||
//Selection Sorting
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
int min=i;
|
||||
for(int j=i+1; j<6; j++)
|
||||
{
|
||||
if(Array[j]<Array[min])
|
||||
{
|
||||
min=j; //Finding the smallest number in Array
|
||||
}
|
||||
}
|
||||
int temp =Array[i];
|
||||
Array[i]=Array[min];
|
||||
Array[min]=temp;
|
||||
}
|
||||
|
||||
//Output
|
||||
cout<<"\nSorted Array : ";
|
||||
for(int i=0; i<6; i++)
|
||||
{
|
||||
cout<<Array[i]<<"\t";
|
||||
}
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
#include<iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int size=10;
|
||||
int array[size];
|
||||
// Input
|
||||
cout<<"\nHow many numbers do want to enter in unsorted array : ";
|
||||
cin>>size;
|
||||
cout<<"\nEnter the numbers for unsorted array : ";
|
||||
for (int i = 0; i < size; i++)
|
||||
{
|
||||
cin>>array[i];
|
||||
}
|
||||
|
||||
// Sorting
|
||||
for (int i = size/2; i>0 ; i=i/2)
|
||||
{
|
||||
for (int j = i; j <size ; j++)
|
||||
{
|
||||
for (int k = j-i; k>=0; k=k-i)
|
||||
{
|
||||
if (array[k]<array[k+i])
|
||||
{
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
int temp=array[k+i];
|
||||
array[k+i]=array[k];
|
||||
array[k]=temp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Output
|
||||
cout<<"\nSorted array : ";
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
cout<<array[i]<<"\t";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
// C++ program to sort an array using bucket sort
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
|
||||
// Function to sort arr[] of size n using bucket sort
|
||||
void bucketSort(float arr[], int n)
|
||||
{
|
||||
// 1) Create n empty buckets
|
||||
vector<float> b[n];
|
||||
|
||||
// 2) Put array elements in different buckets
|
||||
for (int i=0; i<n; i++)
|
||||
{
|
||||
int bi = n*arr[i]; // Index in bucket
|
||||
b[bi].push_back(arr[i]);
|
||||
}
|
||||
|
||||
// 3) Sort individual buckets
|
||||
for (int i=0; i<n; i++)
|
||||
sort(b[i].begin(), b[i].end());
|
||||
|
||||
// 4) Concatenate all buckets into arr[]
|
||||
int index = 0;
|
||||
for (int i = 0; i < n; i++)
|
||||
for (int j = 0; j < b[i].size(); j++)
|
||||
arr[index++] = b[i][j];
|
||||
}
|
||||
|
||||
/* Driver program to test above funtion */
|
||||
int main()
|
||||
{
|
||||
float arr[] = {0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434};
|
||||
int n = sizeof(arr)/sizeof(arr[0]);
|
||||
bucketSort(arr, n);
|
||||
|
||||
cout << "Sorted array is \n";
|
||||
for (int i=0; i<n; i++)
|
||||
cout << arr[i] << " ";
|
||||
return 0;
|
||||
}
|
||||
@@ -1,48 +1,47 @@
|
||||
#include<stdio.h>
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// Number of vertices in the graph
|
||||
#define V 4
|
||||
|
||||
|
||||
void printSolution(int color[]);
|
||||
|
||||
|
||||
/* A utility function to check if the current color assignment
|
||||
is safe for vertex v */
|
||||
bool isSafe (int v, bool graph[V][V], int color[], int c)
|
||||
bool isSafe(int v, bool graph[V][V], int color[], int c)
|
||||
{
|
||||
for (int i = 0; i < V; i++)
|
||||
if (graph[v][i] && c == color[i])
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/* A recursive utility function to solve m coloring problem */
|
||||
void graphColoring(bool graph[V][V], int m, int color[], int v)
|
||||
{
|
||||
/* base case: If all vertices are assigned a color then
|
||||
return true */
|
||||
if (v == V){
|
||||
printSolution(color);
|
||||
if (v == V)
|
||||
{
|
||||
printSolution(color);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
/* Consider this vertex v and try different colors */
|
||||
for (int c = 1; c <= m; c++)
|
||||
{
|
||||
/* Check if assignment of color c to v is fine*/
|
||||
if (isSafe(v, graph, color, c))
|
||||
{
|
||||
color[v] = c;
|
||||
|
||||
/* recur to assign colors to rest of the vertices */
|
||||
graphColoring (graph, m, color, v+1);
|
||||
|
||||
|
||||
color[v] = c;
|
||||
|
||||
/* recur to assign colors to rest of the vertices */
|
||||
graphColoring(graph, m, color, v + 1);
|
||||
|
||||
/* If assigning color c doesn't lead to a solution
|
||||
then remove it */
|
||||
color[v] = 0;
|
||||
color[v] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* A utility function to print solution */
|
||||
@@ -50,10 +49,10 @@ void printSolution(int color[])
|
||||
{
|
||||
printf(" Following are the assigned colors \n");
|
||||
for (int i = 0; i < V; i++)
|
||||
printf(" %d ", color[i]);
|
||||
printf(" %d ", color[i]);
|
||||
printf("\n");
|
||||
}
|
||||
|
||||
|
||||
// driver program to test above function
|
||||
int main()
|
||||
{
|
||||
@@ -64,18 +63,19 @@ int main()
|
||||
| / |
|
||||
(0)---(1)
|
||||
*/
|
||||
bool graph[V][V] = {{0, 1, 1, 1},
|
||||
bool graph[V][V] = {
|
||||
{0, 1, 1, 1},
|
||||
{1, 0, 1, 0},
|
||||
{1, 1, 0, 1},
|
||||
{1, 0, 1, 0},
|
||||
};
|
||||
int m = 3; // Number of colors
|
||||
|
||||
int color[V];
|
||||
int color[V];
|
||||
|
||||
for (int i = 0; i < V; i++)
|
||||
for (int i = 0; i < V; i++)
|
||||
color[i] = 0;
|
||||
|
||||
|
||||
graphColoring(graph, m, color, 0);
|
||||
return 0;
|
||||
}
|
||||
68
backtracking/knight_tour.cpp
Normal file
68
backtracking/knight_tour.cpp
Normal file
@@ -0,0 +1,68 @@
|
||||
#include <iostream>
|
||||
# define n 8
|
||||
|
||||
/**
|
||||
A knight's tour is a sequence of moves of a knight on a chessboard
|
||||
such that the knight visits every square only once. If the knight
|
||||
ends on a square that is one knight's move from the beginning
|
||||
square (so that it could tour the board again immediately, following
|
||||
the same path), the tour is closed; otherwise, it is open.
|
||||
**/
|
||||
|
||||
using namespace std;
|
||||
bool issafe(int x,int y,int sol[n][n])
|
||||
{
|
||||
return (x<n && x>=0 && y<n && y>=0 && sol[x][y]==-1);
|
||||
|
||||
}
|
||||
bool solve(int x,int y, int mov, int sol[n][n], int xmov[n], int ymov[n])
|
||||
{
|
||||
int k,xnext,ynext;
|
||||
|
||||
if(mov == n*n)
|
||||
return true;
|
||||
|
||||
for(k=0;k<8;k++)
|
||||
{
|
||||
xnext=x+xmov[k];
|
||||
ynext=y+ymov[k];
|
||||
|
||||
if(issafe(xnext,ynext,sol))
|
||||
{
|
||||
sol[xnext][ynext]=mov;
|
||||
|
||||
if(solve(xnext,ynext,mov+1,sol,xmov,ymov)==true)
|
||||
return true;
|
||||
else
|
||||
sol[xnext][ynext]=-1;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
int main()
|
||||
{
|
||||
//initialize();
|
||||
|
||||
int sol[n][n];
|
||||
int i,j;
|
||||
for(i=0;i<n;i++)
|
||||
for(j=0;j<n;j++)
|
||||
sol[i][j]=-1;
|
||||
|
||||
int xmov[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
|
||||
int ymov[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
|
||||
sol[0][0]=0;
|
||||
|
||||
bool flag=solve(0,0,1,sol,xmov,ymov);
|
||||
if(flag==false)
|
||||
cout<<"solution doesnot exist \n";
|
||||
else
|
||||
{
|
||||
for(i=0;i<n;i++)
|
||||
{
|
||||
for(j=0;j<n;j++)
|
||||
cout<<sol[i][j]<<" ";
|
||||
cout<<"\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
27
backtracking/minimax.cpp
Normal file
27
backtracking/minimax.cpp
Normal file
@@ -0,0 +1,27 @@
|
||||
#include <cmath>
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
|
||||
using std::cout;
|
||||
using std::endl;
|
||||
using std::max;
|
||||
using std::min;
|
||||
using std::vector;
|
||||
|
||||
int minimax(int depth, int node_index, bool is_max, vector<int> scores,
|
||||
int height) {
|
||||
if (depth == height)
|
||||
return scores[node_index];
|
||||
|
||||
int v1 = minimax(depth + 1, node_index * 2, !is_max, scores, height);
|
||||
int v2 = minimax(depth + 1, node_index * 2 + 1, !is_max, scores, height);
|
||||
|
||||
return is_max ? max(v1, v2) : min(v1, v2);
|
||||
}
|
||||
|
||||
int main() {
|
||||
vector<int> scores = { 90, 23, 6, 33, 21, 65, 123, 34423 };
|
||||
int height = log2(scores.size());
|
||||
|
||||
cout << "Optimal value: " << minimax(0, 0, true, scores, height) << endl;
|
||||
}
|
||||
@@ -1,82 +1,77 @@
|
||||
#include<iostream>
|
||||
#include <iostream>
|
||||
#define N 4
|
||||
using namespace std;
|
||||
|
||||
void printSolution(int board[N][N])
|
||||
{
|
||||
cout<<"\n";
|
||||
cout << "\n";
|
||||
for (int i = 0; i < N; i++)
|
||||
{
|
||||
for (int j = 0; j < N; j++)
|
||||
cout<<""<<board[i][j];
|
||||
cout<<"\n";
|
||||
cout << "" << board[i][j];
|
||||
cout << "\n";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool isSafe(int board[N][N], int row, int col)
|
||||
{
|
||||
int i, j;
|
||||
|
||||
|
||||
/* Check this row on left side */
|
||||
for (i = 0; i < col; i++)
|
||||
if (board[row][i])
|
||||
return false;
|
||||
|
||||
|
||||
/* Check upper diagonal on left side */
|
||||
for (i=row, j=col; i>=0 && j>=0; i--, j--)
|
||||
for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
|
||||
if (board[i][j])
|
||||
return false;
|
||||
|
||||
|
||||
/* Check lower diagonal on left side */
|
||||
for (i=row, j=col; j>=0 && i<N; i++, j--)
|
||||
for (i = row, j = col; j >= 0 && i < N; i++, j--)
|
||||
if (board[i][j])
|
||||
return false;
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
void solveNQ(int board[N][N], int col)
|
||||
{
|
||||
|
||||
if (col >= N){
|
||||
|
||||
if (col >= N)
|
||||
{
|
||||
printSolution(board);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
/* Consider this column and try placing
|
||||
this queen in all rows one by one */
|
||||
for (int i = 0; i < N; i++)
|
||||
{
|
||||
/* Check if queen can be placed on
|
||||
board[i][col] */
|
||||
if ( isSafe(board, i, col) )
|
||||
if (isSafe(board, i, col))
|
||||
{
|
||||
/* Place this queen in board[i][col] */
|
||||
// cout<<"\n"<<col<<"can place"<<i;
|
||||
// cout<<"\n"<<col<<"can place"<<i;
|
||||
board[i][col] = 1;
|
||||
|
||||
|
||||
/* recur to place rest of the queens */
|
||||
solveNQ(board, col + 1);
|
||||
|
||||
|
||||
board[i][col] = 0; // BACKTRACK
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int board[N][N] = { {0, 0, 0, 0},
|
||||
{0, 0, 0, 0},
|
||||
{0, 0, 0, 0},
|
||||
{0, 0, 0, 0}
|
||||
};
|
||||
|
||||
solveNQ(board, 0);
|
||||
|
||||
int board[N][N] = {{0, 0, 0, 0},
|
||||
{0, 0, 0, 0},
|
||||
{0, 0, 0, 0},
|
||||
{0, 0, 0, 0}};
|
||||
|
||||
solveNQ(board, 0);
|
||||
return 0;
|
||||
}
|
||||
50
backtracking/nqueen_print_all_solutions.cpp
Normal file
50
backtracking/nqueen_print_all_solutions.cpp
Normal file
@@ -0,0 +1,50 @@
|
||||
#include <iostream>
|
||||
#define n 4
|
||||
|
||||
void PrintSol(int Board[n][n]) {
|
||||
for (int i = 0; i < n; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
std::cout << Board[i][j] << " ";
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
bool CanIMove(int Board[n][n], int row, int col) {
|
||||
/// check in the row
|
||||
for (int i = 0; i < col; i++) {
|
||||
if (Board[row][i] == 1)
|
||||
return false;
|
||||
}
|
||||
/// check the first diagonal
|
||||
for (int i = row, j = col; i >= 0 && j >= 0; i--, j--) {
|
||||
if (Board[i][j] == 1)
|
||||
return false;
|
||||
}
|
||||
/// check the second diagonal
|
||||
for (int i = row, j = col; i <= n - 1 && j >= 0; i++, j--) {
|
||||
if (Board[i][j] == 1)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void NQueenSol(int Board[n][n], int col) {
|
||||
if (col >= n) {
|
||||
PrintSol(Board);
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (CanIMove(Board, i, col)) {
|
||||
Board[i][col] = 1;
|
||||
NQueenSol(Board, col + 1);
|
||||
Board[i][col] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int Board[n][n] = {0};
|
||||
NQueenSol(Board, 0);
|
||||
}
|
||||
73
backtracking/rat_maze.cpp
Normal file
73
backtracking/rat_maze.cpp
Normal file
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
A Maze is given as N*N binary matrix of blocks where source block is the upper
|
||||
left most block i.e., maze[0][0] and destination block is lower rightmost
|
||||
block i.e., maze[N-1][N-1]. A rat starts from source and has to reach destination.
|
||||
The rat can move only in two directions: forward and down. In the maze matrix,
|
||||
0 means the block is dead end and 1 means the block can be used in the path
|
||||
from source to destination.
|
||||
*/
|
||||
#include <iostream>
|
||||
#define size 4
|
||||
|
||||
using namespace std;
|
||||
|
||||
int solveMaze(int currposrow, int currposcol, int maze[size][size], int soln[size][size])
|
||||
{
|
||||
if ((currposrow == size - 1) && (currposcol == size - 1))
|
||||
{
|
||||
soln[currposrow][currposcol] = 1;
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
for (int j = 0; j < size; ++j)
|
||||
{
|
||||
cout << soln[i][j];
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
soln[currposrow][currposcol] = 1;
|
||||
|
||||
// if there exist a solution by moving one step ahead in a collumn
|
||||
if ((currposcol < size - 1) && maze[currposrow][currposcol + 1] == 1 && solveMaze(currposrow, currposcol + 1, maze, soln))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
// if there exists a solution by moving one step ahead in a row
|
||||
if ((currposrow < size - 1) && maze[currposrow + 1][currposcol] == 1 && solveMaze(currposrow + 1, currposcol, maze, soln))
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
// the backtracking part
|
||||
soln[currposrow][currposcol] = 0;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char const *argv[])
|
||||
{
|
||||
int maze[size][size] = {
|
||||
{1, 0, 1, 0},
|
||||
{1, 0, 1, 1},
|
||||
{1, 0, 0, 1},
|
||||
{1, 1, 1, 1}};
|
||||
|
||||
int soln[size][size];
|
||||
|
||||
for (int i = 0; i < size; ++i)
|
||||
{
|
||||
for (int j = 0; j < size; ++j)
|
||||
{
|
||||
soln[i][j] = 0;
|
||||
}
|
||||
}
|
||||
|
||||
int currposrow = 0;
|
||||
int currposcol = 0;
|
||||
solveMaze(currposrow, currposcol, maze, soln);
|
||||
return 0;
|
||||
}
|
||||
117
backtracking/sudoku_solve.cpp
Normal file
117
backtracking/sudoku_solve.cpp
Normal file
@@ -0,0 +1,117 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
///N=9;
|
||||
int n = 9;
|
||||
|
||||
bool isPossible(int mat[][9], int i, int j, int no)
|
||||
{
|
||||
///Row or col nahin hona chahiye
|
||||
for (int x = 0; x < n; x++)
|
||||
{
|
||||
if (mat[x][j] == no || mat[i][x] == no)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subgrid mein nahi hona chahiye
|
||||
int sx = (i / 3) * 3;
|
||||
int sy = (j / 3) * 3;
|
||||
|
||||
for (int x = sx; x < sx + 3; x++)
|
||||
{
|
||||
for (int y = sy; y < sy + 3; y++)
|
||||
{
|
||||
if (mat[x][y] == no)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
void printMat(int mat[][9])
|
||||
{
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
for (int j = 0; j < n; j++)
|
||||
{
|
||||
cout << mat[i][j] << " ";
|
||||
if ((j + 1) % 3 == 0)
|
||||
{
|
||||
cout << '\t';
|
||||
}
|
||||
}
|
||||
if ((i + 1) % 3 == 0)
|
||||
{
|
||||
cout << endl;
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
}
|
||||
|
||||
bool solveSudoku(int mat[][9], int i, int j)
|
||||
{
|
||||
///Base Case
|
||||
if (i == 9)
|
||||
{
|
||||
///Solve kr chuke hain for 9 rows already
|
||||
printMat(mat);
|
||||
return true;
|
||||
}
|
||||
|
||||
///Crossed the last Cell in the row
|
||||
if (j == 9)
|
||||
{
|
||||
return solveSudoku(mat, i + 1, 0);
|
||||
}
|
||||
|
||||
///Blue Cell - Skip
|
||||
if (mat[i][j] != 0)
|
||||
{
|
||||
return solveSudoku(mat, i, j + 1);
|
||||
}
|
||||
///White Cell
|
||||
///Try to place every possible no
|
||||
for (int no = 1; no <= 9; no++)
|
||||
{
|
||||
if (isPossible(mat, i, j, no))
|
||||
{
|
||||
///Place the no - assuming solution aa jayega
|
||||
mat[i][j] = no;
|
||||
bool aageKiSolveHui = solveSudoku(mat, i, j + 1);
|
||||
if (aageKiSolveHui)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
///Nahin solve hui
|
||||
///loop will place the next no.
|
||||
}
|
||||
}
|
||||
///Sare no try kr liey, kisi se bhi solve nahi hui
|
||||
mat[i][j] = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
|
||||
int mat[9][9] =
|
||||
{{5, 3, 0, 0, 7, 0, 0, 0, 0},
|
||||
{6, 0, 0, 1, 9, 5, 0, 0, 0},
|
||||
{0, 9, 8, 0, 0, 0, 0, 6, 0},
|
||||
{8, 0, 0, 0, 6, 0, 0, 0, 3},
|
||||
{4, 0, 0, 8, 0, 3, 0, 0, 1},
|
||||
{7, 0, 0, 0, 2, 0, 0, 0, 6},
|
||||
{0, 6, 0, 0, 0, 0, 2, 8, 0},
|
||||
{0, 0, 0, 4, 1, 9, 0, 0, 5},
|
||||
{0, 0, 0, 0, 8, 0, 0, 7, 9}};
|
||||
|
||||
printMat(mat);
|
||||
cout << "Solution " << endl;
|
||||
solveSudoku(mat, 0, 0);
|
||||
|
||||
return 0;
|
||||
}
|
||||
53
computer_oriented_statistical_methods/Bisection_method.CPP
Normal file
53
computer_oriented_statistical_methods/Bisection_method.CPP
Normal file
@@ -0,0 +1,53 @@
|
||||
#include <iostream.h>
|
||||
#include <conio.h>
|
||||
#include <math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i, 3) - (4 * i) - 9); // original equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a, b, x, z;
|
||||
clrscr();
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
z = eq(i);
|
||||
if (z >= 0)
|
||||
{
|
||||
b = i;
|
||||
a = --i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout << "\nFirst initial: " << a;
|
||||
cout << "\nSecond initial: " << b;
|
||||
for (i = 0; i < 100; i++)
|
||||
{
|
||||
x = (a + b) / 2;
|
||||
z = eq(x);
|
||||
cout << "\n\nz: " << z << "\t[" << a << " , " << b << " | Bisect: " << x << "]";
|
||||
|
||||
if (z < 0)
|
||||
{
|
||||
a = x;
|
||||
}
|
||||
else
|
||||
{
|
||||
b = x;
|
||||
}
|
||||
|
||||
if (z > 0 && z < 0.0009) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout << "\n\nRoot: " << x;
|
||||
getch();
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
int main()
|
||||
{
|
||||
int mat_size, i, j, step;
|
||||
|
||||
cout << "Matrix size: ";
|
||||
cin >> mat_size;
|
||||
|
||||
double mat[mat_size + 1][mat_size + 1], x[mat_size][mat_size + 1];
|
||||
|
||||
cout << endl
|
||||
<< "Enter value of the matrix: " << endl;
|
||||
for (i = 0; i < mat_size; i++)
|
||||
{
|
||||
for (j = 0; j <= mat_size; j++)
|
||||
{
|
||||
cin >> mat[i][j]; //Enter (mat_size*mat_size) value of the matrix.
|
||||
}
|
||||
}
|
||||
|
||||
for (step = 0; step < mat_size - 1; step++)
|
||||
{
|
||||
for (i = step; i < mat_size - 1; i++)
|
||||
{
|
||||
double a = (mat[i + 1][step] / mat[step][step]);
|
||||
|
||||
for (j = step; j <= mat_size; j++)
|
||||
mat[i + 1][j] = mat[i + 1][j] - (a * mat[step][j]);
|
||||
}
|
||||
}
|
||||
|
||||
cout << endl
|
||||
<< "Matrix using Gaussian Elimination method: " << endl;
|
||||
for (i = 0; i < mat_size; i++)
|
||||
{
|
||||
for (j = 0; j <= mat_size; j++)
|
||||
{
|
||||
x[i][j] = mat[i][j];
|
||||
cout << mat[i][j] << " ";
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
cout << endl
|
||||
<< "Value of the Gaussian Elimination method: " << endl;
|
||||
for (i = mat_size - 1; i >= 0; i--)
|
||||
{
|
||||
double sum = 0;
|
||||
for (j = mat_size - 1; j > i; j--)
|
||||
{
|
||||
x[i][j] = x[j][j] * x[i][j];
|
||||
sum = x[i][j] + sum;
|
||||
}
|
||||
if (x[i][i] == 0)
|
||||
x[i][i] = 0;
|
||||
else
|
||||
x[i][i] = (x[i][mat_size] - sum) / (x[i][i]);
|
||||
|
||||
cout << "x" << i << "= " << x[i][i] << endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
53
computer_oriented_statistical_methods/Newton_Raphson.CPP
Normal file
53
computer_oriented_statistical_methods/Newton_Raphson.CPP
Normal file
@@ -0,0 +1,53 @@
|
||||
#include <iostream.h>
|
||||
#include <conio.h>
|
||||
#include <math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i, 3) - (4 * i) - 9); // original equation
|
||||
}
|
||||
float eq_der(float i)
|
||||
{
|
||||
return ((3 * pow(i, 2)) - 4); // derivative of equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a, b, z, c, m, n;
|
||||
clrscr();
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
z = eq(i);
|
||||
if (z >= 0)
|
||||
{
|
||||
b = i;
|
||||
a = --i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout << "\nFirst initial: " << a;
|
||||
cout << "\nSecond initial: " << b;
|
||||
c = (a + b) / 2;
|
||||
|
||||
for (i = 0; i < 100; i++)
|
||||
{
|
||||
float h;
|
||||
m = eq(c);
|
||||
n = eq_der(c);
|
||||
|
||||
z = c - (m / n);
|
||||
c = z;
|
||||
|
||||
if (m > 0 && m < 0.009) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout << "\n\nRoot: " << z;
|
||||
getch();
|
||||
}
|
||||
49
computer_oriented_statistical_methods/Secant_method.CPP
Normal file
49
computer_oriented_statistical_methods/Secant_method.CPP
Normal file
@@ -0,0 +1,49 @@
|
||||
#include <iostream.h>
|
||||
#include <conio.h>
|
||||
#include <math.h>
|
||||
|
||||
float eq(float i)
|
||||
{
|
||||
return (pow(i, 3) - (4 * i) - 9); // original equation
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float a, b, z, c, m, n;
|
||||
clrscr();
|
||||
for (int i = 0; i < 100; i++)
|
||||
{
|
||||
z = eq(i);
|
||||
if (z >= 0)
|
||||
{
|
||||
b = i;
|
||||
a = --i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
|
||||
START:
|
||||
|
||||
cout << "\nFirst initial: " << a;
|
||||
cout << "\nSecond initial: " << b;
|
||||
for (i = 0; i < 100; i++)
|
||||
{
|
||||
float h, d;
|
||||
m = eq(a);
|
||||
n = eq(b);
|
||||
|
||||
c = ((a * n) - (b * m)) / (n - m);
|
||||
a = b;
|
||||
b = c;
|
||||
|
||||
z = eq(c);
|
||||
if (z > 0 && z < 0.09) // stoping criteria
|
||||
{
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
|
||||
END:
|
||||
cout << "\n\nRoot: " << c;
|
||||
getch();
|
||||
}
|
||||
35
computer_oriented_statistical_methods/false-position.cpp
Normal file
35
computer_oriented_statistical_methods/false-position.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include<stdlib.h>
|
||||
#include <math.h>
|
||||
#include <iostream>
|
||||
float eq(float i) {
|
||||
return (pow(i, 3) - (4 * i) - 9); // origial equation
|
||||
}
|
||||
int main() {
|
||||
float a, b, z, c, m, n;
|
||||
system("clear");
|
||||
for (int i = 0; i < 100; i++) {
|
||||
z = eq(i);
|
||||
if (z >= 0) {
|
||||
b = i;
|
||||
a = --i;
|
||||
goto START;
|
||||
}
|
||||
}
|
||||
START:
|
||||
std::cout << "\nFirst initial: " << a;
|
||||
std::cout << "\nSecond initial: " << b;
|
||||
for (int i = 0; i < 100; i++) {
|
||||
float h, d;
|
||||
m = eq(a);
|
||||
n = eq(b);
|
||||
c = ((a * n) - (b * m)) / (n - m);
|
||||
a = c;
|
||||
z = eq(c);
|
||||
if (z > 0 && z < 0.09) { // stoping criteria
|
||||
goto END;
|
||||
}
|
||||
}
|
||||
END:
|
||||
std::cout << "\n\nRoot: " << c;
|
||||
system("pause");
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
#include <conio.h>
|
||||
#include <iostream.h>
|
||||
#include <math.h>
|
||||
float eq(float y)
|
||||
{
|
||||
return ((3 * y) - (cos(y)) - 2);
|
||||
}
|
||||
float eqd(float y)
|
||||
{
|
||||
return ((0.5) * ((cos(y)) + 2));
|
||||
}
|
||||
|
||||
void main()
|
||||
{
|
||||
float y, x1, x2, x3, sum, s, a, f1, f2, gd;
|
||||
int i, n;
|
||||
|
||||
clrscr();
|
||||
for (i = 0; i < 10; i++)
|
||||
{
|
||||
sum = eq(y);
|
||||
cout << "value of equation at " << i << " " << sum << "\n";
|
||||
y++;
|
||||
}
|
||||
cout << "enter the x1->";
|
||||
cin >> x1;
|
||||
cout << "enter the no iteration to perform->\n";
|
||||
cin >> n;
|
||||
|
||||
for (i = 0; i <= n; i++)
|
||||
{
|
||||
x2 = eqd(x1);
|
||||
cout << "\nenter the x2->" << x2;
|
||||
x1 = x2;
|
||||
}
|
||||
getch();
|
||||
}
|
||||
@@ -3,20 +3,23 @@
|
||||
|
||||
using namespace std;
|
||||
|
||||
typedef struct node {
|
||||
typedef struct node
|
||||
{
|
||||
int data;
|
||||
int height;
|
||||
struct node* left;
|
||||
struct node* right;
|
||||
}node;
|
||||
struct node *left;
|
||||
struct node *right;
|
||||
} node;
|
||||
|
||||
int max(int a, int b) {
|
||||
int max(int a, int b)
|
||||
{
|
||||
return a > b ? a : b;
|
||||
}
|
||||
|
||||
// Returns a new Node
|
||||
|
||||
node* createNode(int data) {
|
||||
node *createNode(int data)
|
||||
{
|
||||
node *nn = new node();
|
||||
nn->data = data;
|
||||
nn->height = 0;
|
||||
@@ -27,21 +30,24 @@ node* createNode(int data) {
|
||||
|
||||
// Returns height of tree
|
||||
|
||||
int height(node *root) {
|
||||
if(root==NULL)
|
||||
int height(node *root)
|
||||
{
|
||||
if (root == NULL)
|
||||
return 0;
|
||||
return 1 + max(height(root->left), height(root->right));
|
||||
}
|
||||
|
||||
// Returns difference between height of left and right subtree
|
||||
|
||||
int getBalance(node *root) {
|
||||
int getBalance(node *root)
|
||||
{
|
||||
return height(root->left) - height(root->right);
|
||||
}
|
||||
|
||||
// Returns Node after Right Rotation
|
||||
|
||||
node* rightRotate(node *root) {
|
||||
node *rightRotate(node *root)
|
||||
{
|
||||
node *t = root->left;
|
||||
node *u = t->right;
|
||||
t->right = root;
|
||||
@@ -51,7 +57,8 @@ node* rightRotate(node *root) {
|
||||
|
||||
// Returns Node after Left Rotation
|
||||
|
||||
node* leftRotate(node *root) {
|
||||
node *leftRotate(node *root)
|
||||
{
|
||||
node *t = root->right;
|
||||
node *u = t->left;
|
||||
t->left = root;
|
||||
@@ -61,57 +68,65 @@ node* leftRotate(node *root) {
|
||||
|
||||
// Returns node with minimum value in the tree
|
||||
|
||||
node* minValue(node* root) {
|
||||
if(root->left==NULL)
|
||||
node *minValue(node *root)
|
||||
{
|
||||
if (root->left == NULL)
|
||||
return root;
|
||||
return minValue(root->left);
|
||||
}
|
||||
|
||||
// Balanced Insertion
|
||||
|
||||
node* insert(node* root, int item) {
|
||||
node *insert(node *root, int item)
|
||||
{
|
||||
node *nn = createNode(item);
|
||||
if(root == NULL)
|
||||
if (root == NULL)
|
||||
return nn;
|
||||
if(item<root->data)
|
||||
if (item < root->data)
|
||||
root->left = insert(root->left, item);
|
||||
else
|
||||
root->right = insert(root->right, item);
|
||||
int b = getBalance(root);
|
||||
if(b>1) {
|
||||
if(getBalance(root->left)<0)
|
||||
root->left = leftRotate(root->left); // Left-Right Case
|
||||
return rightRotate(root); // Left-Left Case
|
||||
if (b > 1)
|
||||
{
|
||||
if (getBalance(root->left) < 0)
|
||||
root->left = leftRotate(root->left); // Left-Right Case
|
||||
return rightRotate(root); // Left-Left Case
|
||||
}
|
||||
else if(b<-1) {
|
||||
if(getBalance(root->right)>0)
|
||||
root->right = rightRotate(root->right); // Right-Left Case
|
||||
return leftRotate(root); // Right-Right Case
|
||||
else if (b < -1)
|
||||
{
|
||||
if (getBalance(root->right) > 0)
|
||||
root->right = rightRotate(root->right); // Right-Left Case
|
||||
return leftRotate(root); // Right-Right Case
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
// Balanced Deletion
|
||||
|
||||
node* deleteNode(node *root, int key) {
|
||||
if(root == NULL)
|
||||
node *deleteNode(node *root, int key)
|
||||
{
|
||||
if (root == NULL)
|
||||
return root;
|
||||
if(key < root->data)
|
||||
if (key < root->data)
|
||||
root->left = deleteNode(root->left, key);
|
||||
else if(key > root->data)
|
||||
else if (key > root->data)
|
||||
root->right = deleteNode(root->right, key);
|
||||
|
||||
else {
|
||||
else
|
||||
{
|
||||
// Node to be deleted is leaf node or have only one Child
|
||||
if(!root->right) {
|
||||
node* temp = root->left;
|
||||
delete(root);
|
||||
if (!root->right)
|
||||
{
|
||||
node *temp = root->left;
|
||||
delete (root);
|
||||
root = NULL;
|
||||
return temp;
|
||||
}
|
||||
else if(!root->left) {
|
||||
node* temp = root->right;
|
||||
delete(root);
|
||||
else if (!root->left)
|
||||
{
|
||||
node *temp = root->right;
|
||||
delete (root);
|
||||
root = NULL;
|
||||
return temp;
|
||||
}
|
||||
@@ -124,36 +139,38 @@ node* deleteNode(node *root, int key) {
|
||||
return root;
|
||||
}
|
||||
|
||||
|
||||
// LevelOrder (Breadth First Search)
|
||||
|
||||
void levelOrder(node* root) {
|
||||
queue<node*> q;
|
||||
void levelOrder(node *root)
|
||||
{
|
||||
queue<node *> q;
|
||||
q.push(root);
|
||||
while(!q.empty()) {
|
||||
while (!q.empty())
|
||||
{
|
||||
root = q.front();
|
||||
cout<<root->data<<" ";
|
||||
cout << root->data << " ";
|
||||
q.pop();
|
||||
if(root->left)
|
||||
if (root->left)
|
||||
q.push(root->left);
|
||||
if(root->right)
|
||||
if (root->right)
|
||||
q.push(root->right);
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
int main()
|
||||
{
|
||||
// Testing AVL Tree
|
||||
node *root = NULL;
|
||||
int i;
|
||||
for(i = 1 ; i <= 7 ; i++)
|
||||
for (i = 1; i <= 7; i++)
|
||||
root = insert(root, i);
|
||||
cout<<"LevelOrder: ";
|
||||
cout << "LevelOrder: ";
|
||||
levelOrder(root);
|
||||
root = deleteNode(root, 1); // Deleting key with value 1
|
||||
cout<<"\nLevelOrder: ";
|
||||
cout << "\nLevelOrder: ";
|
||||
levelOrder(root);
|
||||
root = deleteNode(root, 4); // Deletin key with value 4
|
||||
cout<<"\nLevelOrder: ";
|
||||
root = deleteNode(root, 4); // Deletin key with value 4
|
||||
cout << "\nLevelOrder: ";
|
||||
levelOrder(root);
|
||||
return 0;
|
||||
}
|
||||
218
data_structure/Binary Search Tree.cpp
Normal file
218
data_structure/Binary Search Tree.cpp
Normal file
@@ -0,0 +1,218 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
struct node
|
||||
{
|
||||
int val;
|
||||
node *left;
|
||||
node *right;
|
||||
};
|
||||
|
||||
struct queue
|
||||
{
|
||||
node *t[100];
|
||||
int front;
|
||||
int rear;
|
||||
};
|
||||
|
||||
queue q;
|
||||
|
||||
void enqueue(node *n)
|
||||
{
|
||||
q.t[q.rear++] = n;
|
||||
}
|
||||
|
||||
node *dequeue()
|
||||
{
|
||||
return (q.t[q.front++]);
|
||||
}
|
||||
|
||||
void Insert(node *n, int x)
|
||||
{
|
||||
if (x < n->val)
|
||||
{
|
||||
if (n->left == NULL)
|
||||
{
|
||||
node *temp = new node;
|
||||
temp->val = x;
|
||||
temp->left = NULL;
|
||||
temp->right = NULL;
|
||||
n->left = temp;
|
||||
}
|
||||
else
|
||||
{
|
||||
Insert(n->left, x);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (n->right == NULL)
|
||||
{
|
||||
node *temp = new node;
|
||||
temp->val = x;
|
||||
temp->left = NULL;
|
||||
temp->right = NULL;
|
||||
n->left = temp;
|
||||
}
|
||||
else
|
||||
{
|
||||
Insert(n->right, x);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int findMaxInLeftST(node *n)
|
||||
{
|
||||
while (n->right != NULL)
|
||||
{
|
||||
n = n->right;
|
||||
}
|
||||
return n->val;
|
||||
}
|
||||
|
||||
void Remove(node *p, node *n, int x)
|
||||
{
|
||||
if (n->val == x)
|
||||
{
|
||||
if (n->right == NULL && n->left == NULL)
|
||||
{
|
||||
if (x < p->val)
|
||||
{
|
||||
p->right = NULL;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left = NULL;
|
||||
}
|
||||
}
|
||||
else if (n->right == NULL)
|
||||
{
|
||||
if (x < p->val)
|
||||
{
|
||||
p->right = n->left;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left = n->left;
|
||||
}
|
||||
}
|
||||
else if (n->left == NULL)
|
||||
{
|
||||
if (x < p->val)
|
||||
{
|
||||
p->right = n->right;
|
||||
}
|
||||
else
|
||||
{
|
||||
p->left = n->right;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
int y = findMaxInLeftST(n->left);
|
||||
n->val = y;
|
||||
Remove(n, n->right, y);
|
||||
}
|
||||
}
|
||||
else if (x < n->val)
|
||||
{
|
||||
Remove(n, n->left, x);
|
||||
}
|
||||
else
|
||||
{
|
||||
Remove(n, n->right, x);
|
||||
}
|
||||
}
|
||||
|
||||
void BFT(node *n)
|
||||
{
|
||||
if (n != NULL)
|
||||
{
|
||||
cout << n->val << " ";
|
||||
enqueue(n->left);
|
||||
enqueue(n->right);
|
||||
BFT(dequeue());
|
||||
}
|
||||
}
|
||||
|
||||
void Pre(node *n)
|
||||
{
|
||||
if (n != NULL)
|
||||
{
|
||||
cout << n->val << " ";
|
||||
Pre(n->left);
|
||||
Pre(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void In(node *n)
|
||||
{
|
||||
if (n != NULL)
|
||||
{
|
||||
In(n->left);
|
||||
cout << n->val << " ";
|
||||
In(n->right);
|
||||
}
|
||||
}
|
||||
|
||||
void Post(node *n)
|
||||
{
|
||||
if (n != NULL)
|
||||
{
|
||||
Post(n->left);
|
||||
Post(n->right);
|
||||
cout << n->val << " ";
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
q.front = 0;
|
||||
q.rear = 0;
|
||||
int value;
|
||||
int ch;
|
||||
node *root = new node;
|
||||
cout << "\nEnter the value of root node :";
|
||||
cin >> value;
|
||||
root->val = value;
|
||||
root->left = NULL;
|
||||
root->right = NULL;
|
||||
do
|
||||
{
|
||||
cout << "\n1. Insert";
|
||||
cout << "\n2. Delete";
|
||||
cout << "\n3. Breadth First";
|
||||
cout << "\n4. Preorder Depth First";
|
||||
cout << "\n5. Inorder Depth First";
|
||||
cout << "\n6. Postorder Depth First";
|
||||
|
||||
cout << "\nEnter Your Choice : ";
|
||||
cin >> ch;
|
||||
int x;
|
||||
switch (ch)
|
||||
{
|
||||
case 1:
|
||||
cout << "\nEnter the value to be Inserted : ";
|
||||
cin >> x;
|
||||
Insert(root, x);
|
||||
break;
|
||||
case 2:
|
||||
cout << "\nEnter the value to be Deleted : ";
|
||||
cin >> x;
|
||||
Remove(root, root, x);
|
||||
break;
|
||||
case 3:
|
||||
BFT(root);
|
||||
break;
|
||||
case 4:
|
||||
Pre(root);
|
||||
break;
|
||||
case 5:
|
||||
In(root);
|
||||
break;
|
||||
case 6:
|
||||
Post(root);
|
||||
break;
|
||||
}
|
||||
} while (ch != 0);
|
||||
}
|
||||
158
data_structure/Binaryheap.cpp
Normal file
158
data_structure/Binaryheap.cpp
Normal file
@@ -0,0 +1,158 @@
|
||||
// A C++ program to demonstrate common Binary Heap Operations
|
||||
#include <iostream>
|
||||
#include <climits>
|
||||
using namespace std;
|
||||
|
||||
// Prototype of a utility function to swap two integers
|
||||
void swap(int *x, int *y);
|
||||
|
||||
// A class for Min Heap
|
||||
class MinHeap
|
||||
{
|
||||
int *harr; // pointer to array of elements in heap
|
||||
int capacity; // maximum possible size of min heap
|
||||
int heap_size; // Current number of elements in min heap
|
||||
public:
|
||||
// Constructor
|
||||
MinHeap(int capacity);
|
||||
|
||||
// to heapify a subtree with the root at given index
|
||||
void MinHeapify(int);
|
||||
|
||||
int parent(int i) { return (i - 1) / 2; }
|
||||
|
||||
// to get index of left child of node at index i
|
||||
int left(int i) { return (2 * i + 1); }
|
||||
|
||||
// to get index of right child of node at index i
|
||||
int right(int i) { return (2 * i + 2); }
|
||||
|
||||
// to extract the root which is the minimum element
|
||||
int extractMin();
|
||||
|
||||
// Decreases key value of key at index i to new_val
|
||||
void decreaseKey(int i, int new_val);
|
||||
|
||||
// Returns the minimum key (key at root) from min heap
|
||||
int getMin() { return harr[0]; }
|
||||
|
||||
// Deletes a key stored at index i
|
||||
void deleteKey(int i);
|
||||
|
||||
// Inserts a new key 'k'
|
||||
void insertKey(int k);
|
||||
};
|
||||
|
||||
// Constructor: Builds a heap from a given array a[] of given size
|
||||
MinHeap::MinHeap(int cap)
|
||||
{
|
||||
heap_size = 0;
|
||||
capacity = cap;
|
||||
harr = new int[cap];
|
||||
}
|
||||
|
||||
// Inserts a new key 'k'
|
||||
void MinHeap::insertKey(int k)
|
||||
{
|
||||
if (heap_size == capacity)
|
||||
{
|
||||
cout << "\nOverflow: Could not insertKey\n";
|
||||
return;
|
||||
}
|
||||
|
||||
// First insert the new key at the end
|
||||
heap_size++;
|
||||
int i = heap_size - 1;
|
||||
harr[i] = k;
|
||||
|
||||
// Fix the min heap property if it is violated
|
||||
while (i != 0 && harr[parent(i)] > harr[i])
|
||||
{
|
||||
swap(&harr[i], &harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Decreases value of key at index 'i' to new_val. It is assumed that
|
||||
// new_val is smaller than harr[i].
|
||||
void MinHeap::decreaseKey(int i, int new_val)
|
||||
{
|
||||
harr[i] = new_val;
|
||||
while (i != 0 && harr[parent(i)] > harr[i])
|
||||
{
|
||||
swap(&harr[i], &harr[parent(i)]);
|
||||
i = parent(i);
|
||||
}
|
||||
}
|
||||
|
||||
// Method to remove minimum element (or root) from min heap
|
||||
int MinHeap::extractMin()
|
||||
{
|
||||
if (heap_size <= 0)
|
||||
return INT_MAX;
|
||||
if (heap_size == 1)
|
||||
{
|
||||
heap_size--;
|
||||
return harr[0];
|
||||
}
|
||||
|
||||
// Store the minimum value, and remove it from heap
|
||||
int root = harr[0];
|
||||
harr[0] = harr[heap_size - 1];
|
||||
heap_size--;
|
||||
MinHeapify(0);
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
// This function deletes key at index i. It first reduced value to minus
|
||||
// infinite, then calls extractMin()
|
||||
void MinHeap::deleteKey(int i)
|
||||
{
|
||||
decreaseKey(i, INT_MIN);
|
||||
extractMin();
|
||||
}
|
||||
|
||||
// A recursive method to heapify a subtree with the root at given index
|
||||
// This method assumes that the subtrees are already heapified
|
||||
void MinHeap::MinHeapify(int i)
|
||||
{
|
||||
int l = left(i);
|
||||
int r = right(i);
|
||||
int smallest = i;
|
||||
if (l < heap_size && harr[l] < harr[i])
|
||||
smallest = l;
|
||||
if (r < heap_size && harr[r] < harr[smallest])
|
||||
smallest = r;
|
||||
if (smallest != i)
|
||||
{
|
||||
swap(&harr[i], &harr[smallest]);
|
||||
MinHeapify(smallest);
|
||||
}
|
||||
}
|
||||
|
||||
// A utility function to swap two elements
|
||||
void swap(int *x, int *y)
|
||||
{
|
||||
int temp = *x;
|
||||
*x = *y;
|
||||
*y = temp;
|
||||
}
|
||||
|
||||
// Driver program to test above functions
|
||||
int main()
|
||||
{
|
||||
MinHeap h(11);
|
||||
h.insertKey(3);
|
||||
h.insertKey(2);
|
||||
h.deleteKey(1);
|
||||
h.insertKey(15);
|
||||
h.insertKey(5);
|
||||
h.insertKey(4);
|
||||
h.insertKey(45);
|
||||
cout << h.extractMin() << " ";
|
||||
cout << h.getMin() << " ";
|
||||
h.decreaseKey(2, 1);
|
||||
cout << h.getMin();
|
||||
return 0;
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user