filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/operating_system/src/memory_management/partitioned_allocation/best_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const proces...
code/operating_system/src/memory_management/partitioned_allocation/first_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const proces...
code/operating_system/src/memory_management/partitioned_allocation/next_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const proces...
code/operating_system/src/memory_management/partitioned_allocation/worst_fit.cpp
/* * Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <queue> #include <unistd.h> class process { public: size_t size; pid_t id; }; class memory { public: size_t size; pid_t id; std::queue<process> allocated_processess; void push(const proces...
code/operating_system/src/processCreation/Processes.c
#include<unistd.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <stdlib.h> #include <stdbool.h> int main(void) { pid_t child; int status; printf("I am the parent, my PID is %d\n", getpid()); printf("My parent's PID is %d\n", getppid()); printf("I am going to create a new...
code/operating_system/src/processCreation/README.md
# Create and handle Processes in Linux operating system. ## Understanding the fork, sleep, wait, exit, getpid, getppid system calls and ps, kill Linux commands. fork() command is used to create a new process. getpid() and getppid() commands are used to display the PID(Process ID) of the child and parent processes. w...
code/operating_system/src/processCreation/vfork.c
/* description: When a vfork system call is issued, the parent process will be suspended until the child process has either completed execution or been replaced with a new executable image via one of the "exec" family of system calls. */ #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #inc...
code/operating_system/src/scheduling/first_come_first_serve/fcfs.cpp
// C++ program for implementation of FCFS // scheduling #include <iostream> using namespace std; // Function to find the waiting time for all // processes void findWaitingTime(int n, int bt[], int wt[]) { // waiting time for first process is 0 wt[0] = 0; // calculating waiting time for (int i = 1; i <...
code/operating_system/src/scheduling/first_come_first_serve/fcfs.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; /* * Part of cosmos from OpenGenus Foundation * */ namespace fcfs { /// <summary> /// Class FCFS will take two inputs, process /// </summary> class FCFS { int[] processes; /...
code/operating_system/src/scheduling/first_come_first_serve/fcfs.java
import java.io.*; class FCFS { public static void main(String args[]) throws Exception { int n,at[],bt[],wt[],tat[]; float AWT=0; InputStreamReader isr=new InputStreamReader(System.in); BufferedReader br=new BufferedReader(isr); System.out.println(“Enter no of process”); n=Integer.parseInt(br.readLine()); ...
code/operating_system/src/scheduling/first_come_first_serve/fcfs.py
# ------------------ # Part of cosmos from OpenGenus Foundations # ------------------ import sys """ Class FCFS accepts dictionary for __processes """ class FCFS: def __init__(self, processes): # initializing private method self.__processes = processes # colling processes self.__wt...
code/operating_system/src/scheduling/first_come_first_serve/fcfs.rs
fn find_waiting_time(bt: &[i32]) -> Vec<i32> { let mut wt = Vec::with_capacity(bt.len()); // Waiting time for first process is 0 wt.push(0); for i in 1..bt.len() { let last_wt = wt.last().cloned().unwrap(); wt.push(bt[i - 1] + last_wt); } wt } fn find_turnaround_time(b...
code/operating_system/src/scheduling/guaranteed_scheduler/guaranteed_scheduling.c
/* Guaranteed scheduler is a specialized scheduling algorithm designed to ensure that specific processes receive a guaranteed share of CPU time. This scheduler represents a basic implementation of a Guaranteed Scheduling Scheduler with Priority Levels. It demonstrates a simple but effective approach to priority-based s...
code/operating_system/src/scheduling/job_sequencing/job_sequencing.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct Job { char id; int deadline; int profit; }; bool jobComparator(const Job &a, const Job &b) { return a.profit > b.profit; } void jobSequence(vector<Job> &jobs) { int n = jobs.size(); sort(jobs.begin(),...
code/operating_system/src/scheduling/multi_level_feedback_queue_scheduling/mlfq.ts
/** * Schedule for running MLFQ simulations and genarating data * https://github.com/Spensaur-K/mlfq-viz */ /** * Config to create a job */ interface JobConfig { id: number; createTime: number; flags: {}[]; runTime: number; ioFreq: number; ioLength: number; } /** * A single job in the simulati...
code/operating_system/src/scheduling/priority_scheduling/priority_scheduling_non_preemptive.c
//Priority scheduling: each process is assigned a priority. Process with highest priority is to be executed first and so on. //Non-preemptive algorithms: once a process enters the running state, it cannot be preempted until it completes its allotted time, #include <stdio.h> #include <stdlib.h> typedef struct process ...
code/operating_system/src/scheduling/priority_scheduling/priority_scheduling_preemptive.c
// Priority scheduling: each process is assigned a priority. Process with // highest priority is to be executed first and so on. #include <stdio.h> #include <stdlib.h> typedef struct process { int pname, pr, at, bt; int ct, wt, rt, tat, flag; // flag=0 means unfinished process }process; int next_process(proces...
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/README.md
# Round robin scheduling in C Just compile the whole, launch the program and follow the steps.
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/queue.c
/* * Part of Cosmos by OpenGenus Foundation. * Basic queue. * Author : ABDOUS Kamel */ #include "queue.h" int init_queue(queue* q, size_t n) { q->vals = malloc(sizeof(QUEUE_VAL) * (n + 1)); if (q->vals == NULL) return (-1); q->n = n + 1; q->head = q->tail = 0; return (0); } void free_queue(queue...
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/queue.h
/* * Part of Cosmos by OpenGenus Foundation. * Basic queue. * Author : ABDOUS Kamel */ #ifndef QUEUE_H #define QUEUE_H #include <stdlib.h> typedef int QUEUE_VAL; typedef struct { QUEUE_VAL* vals; size_t n; int head, tail; } queue; int init_queue(queue* q, size_t n); void free_queue(queue* q); int que...
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_c/round_robin.c
/* * Part of Cosmos by OpenGenus Foundation. * scanf is used for reading integers without any verification, so be careful. * Author : ABDOUS Kamel */ #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include "queue.h" typedef struct { uint32_t turn_around, /* Total turn around of all processes */ ...
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_scheduling.cpp
#include <iostream> #include <vector> using namespace std; int main() { int flag = 0, timeQuantum; int n, remain; int waitTime = 0; cout << "Enter Total Process:\n"; cin >> n; remain = n; vector<int> arrivalTime(n); vector<int> burstTime(n); vector<int> remainingTime(n); for (i...
code/operating_system/src/scheduling/round_robin_scheduling/round_robin_scheduling.java
// Java program for implementation of RR scheduling public class round_robin_scheduling { // Method to find the waiting time for all // processes static void findWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) { // Make a copy of burst times bt[] to store ...
code/operating_system/src/scheduling/shortest_job_first/SJF.ASM
; Author: SYEED MOHD AMEEN ; Email: [email protected] ;----------------------------------------------------------------; ; Shortest Job First ; ;----------------------------------------------------------------; ;--------------------------------------------------...
code/operating_system/src/scheduling/shortest_job_first/sjf.cpp
#include <iostream> #include <stdlib.h> using namespace std; void input_burst_arrival_time(int burst_time[],int process[],int arrival_time[]) { cout<<"Enter burst time and arrival time (in pairs) for four processes : "<<endl; for(int i=0;i<4;i++) // The user is asked to enter burst time and arrival time of 4 pr...
code/operating_system/src/scheduling/shortest_seek_time_first/shortest_seek_time_first.c
// C program for implementing Shortest Seek Time First // Disk Scheduling #include<stdio.h> #include<stdlib.h> // has inbuilt quick sort, abs for ints // For Ascending Order Sort int compare (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } int main() { // Initialization int noOfReque...
code/operating_system/src/scheduling/shortest_seek_time_first/shortest_seek_time_first.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; int main() { int n; cout << "Enter number of process: "; cin >> n; vector<int> burstTime(n); // Array of burst times of processes cout << "Enter Burst time: \n"; for (int i = 0; i < n; i++) { cout << "P...
code/operating_system/src/scheduling/smallest_remaining_time_first/srtf.c
#include <stdio.h> void main() { int arrival_time[10], burst_time[10], temp[10]; int i, smallest, count = 0, time, limit; double wait_time = 0, turnaround_time = 0, end; float average_waiting_time, average_turnaround_time; printf("\nEnter the Total Number of Processes:\t"); scanf("%d", &limit)...
code/operating_system/src/shell/README.md
# Shell ## What is Shell? Simply put, the shell is a program that takes commands from the keyboard and gives them to the operating system to perform. In the old days, it was the only user interface available on a Unix-like system such as Linux. Nowadays, we have graphical user interfaces (GUIs) in addition to command ...
code/operating_system/src/shell/c/README.md
# Implement a Shell in C The Shell include some feature as follows, 1. It is able to run all the single-process commands. 2. It is able to run all the two-process pipelines. 3. It is able to handle input and output redirection. 4. It is able to execute commands in the background. ## What is a Makefile A makefile is ...
code/operating_system/src/shell/c/makefile
all: Shell B013040049_Shell: Shell.o gcc -o Shell Shell.o B013040049_Shell.o: gcc -c Shell.c dep: gcc -M *.c > .depend clean: rm -f *.o Shell .depend
code/operating_system/src/shell/c/shell.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/wait.h> #include <unistd.h> #include <fcntl.h> #define SIZE 50 #define STD_INPUT 0 #define STD_OUTPUT 1 #define TRUE 1 void cd (char *pathname) { /*add cd fuction*/ chdir(pathname); } int main(void) { while (TRUE) { char *argv_...
code/operating_system/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/quantum_algorithms/grovers_algorithm/P1_grover_plot.py
### Imports required for this solution import matplotlib.pyplot as plot import numpy as NP import hashlib from math import sqrt, pi from collections import OrderedDict from statistics import mean ############### ### PlotGraph(n, amplitude): Plots the graph for target value with the highest amplitude. def PlotGraph(...
code/quantum_algorithms/grovers_algorithm/README.md
# Grover’s Algorithm ## Detailed Resources to Understand the Algorithm:- + [Quantum Computing Resources](https://www.topcoder.com/quantum-computing-for-beginners-what-you-need-to-know) - For Beginners + [Topcoder's Tutorial on Grover's Algorithm](https://www.topcoder.com/grovers-algorithm-in-quantum-computing) + [Wikip...
code/quantum_algorithms/shors_algorithm/P1_shor_primefactorization.py
### Imports required for this solution import math import random as rdm ############### ############ Quantum Part (START) ############ ### QuantumMapping: Keeps track of state and amplitude of an electron. class QuantumMapping: def __init__(self, state, amplitude): self.state = state self.ampl...
code/quantum_algorithms/shors_algorithm/README.md
# Shor’s Algorithm ## Detailed Resources to Understand the Algorithm:- + [Quantum Computing Resources](https://www.topcoder.com/quantum-computing-for-beginners-what-you-need-to-know) - For Beginners + [Topcoder's Tutorial on Shor's Algorithm](https://www.topcoder.com/shors-algorithm-in-quantum-computing) + [Wikipedia](...
code/randomized_algorithms/src/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/randomized_algorithms/src/birthday_paradox/birthday_paradox.py
# Part of Cosmos by OpenGenus Foundation import math # Function returns number of people that should be present for a given probability, p def compute_people(p): return math.ceil(math.sqrt(2 * 365 * math.log(1 / (1 - p)))) # Driver code if __name__ == "__main__": print(compute_people(0.5)) print(compute...
code/randomized_algorithms/src/karger_minimum_cut_algorithm/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus) Below Karger’s algorithm can be implemented in O(E) = O(V^2) time ``` 1) Initialize contracted graph CG as copy of original graph 2) While there a...
code/randomized_algorithms/src/karger_minimum_cut_algorithm/karger_minimum_cut_algorithm.cpp
// Karger's algorithm to find Minimum Cut in an // undirected, unweighted and connected graph. #include <stdio.h> #include <stdlib.h> #include <time.h> // a structure to represent a unweighted edge in graph struct Edge { int src, dest; }; // a structure to represent a connected, undirected // and unweighted graph...
code/randomized_algorithms/src/kth_smallest_element_algorithm/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element.java
import java.util.*; class Kth { class MinHeap { int[] harr; int capacity; int heap_size; int parent(int i) { return (i - 1) / 2; } int left(int i) { return ((2 * i )+ 1); } int right(int i) { return ((2 * i) + 2); } int getMin() { return harr[0]; } void replaceMax(int x) { this.harr[0] = x; minHeapify(0)...
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element_algorithm.c
#include <stdio.h> void swap(int *a , int *b) { int temp = *a; *a = *b; *b = temp; } int find_element(int arr[],int n,int k) { for(int i=0; i<n-1; i++) { for(int j=i; j<n-1; j++) { if(arr[j]>arr[j+1]) { swap(&arr[j],&arr[j+1]); } ...
code/randomized_algorithms/src/kth_smallest_element_algorithm/kth_smallest_element_algorithm.cpp
#include <iostream> #include <climits> #include <cstdlib> using namespace std; // Part of Cosmos by OpenGenus Foundation int randomPartition(int arr[], int l, int r); // QuickSort based method. ASSUMPTION: ELEMENTS IN ARR[] ARE DISTINCT int kthSmallest(int arr[], int l, int r, int k) { // If k is smaller than num...
code/randomized_algorithms/src/random_from_stream/random_number_selection_from_a_stream.cpp
// Randomly select a number from stream of numbers. // A function to randomly select a item from stream[0], stream[1], .. stream[i-1] #include <random> #include <iostream> using namespace std; int selectRandom(int x) { static int res; // The resultant random number static int count = 0; //Count of numbers v...
code/randomized_algorithms/src/random_node_linkedlist/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/randomized_algorithms/src/randomized_quick_sort/randomized_quicksort.c
/* * C Program to Implement Quick Sort Using Randomization */ #include <stdio.h> #include <stdlib.h> #define MAX 100 void random_shuffle(int arr[]) { srand(time(NULL)); int i, j, temp; for (i = MAX - 1; i > 0; i--) { j = rand()%(i...
code/randomized_algorithms/src/randomized_quick_sort/randomized_quicksort.cpp
// implementation of quicksort using randomization // by shobhit(dragon540) #include <algorithm> #include <ctime> #include <iostream> #include <vector> void quicksort(std::vector<int> &vect, int low, int high); int part(std::vector<int> &vect, int low, int high); int main() { srand(time(NULL)); std::vector<i...
code/randomized_algorithms/src/reservoir_sampling/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/randomized_algorithms/src/reservoir_sampling/reservoir_sampling.cpp
// An efficient program to randomly select k items from a stream of n items // Part of Cosmos by OpenGenus Foundation #include <iostream> using namespace std; void printArray(int stream[], int n) { for (int i = 0; i < n; i++) printf("%d ", stream[i]); printf("\n"); } // A function to randomly select k...
code/randomized_algorithms/src/reservoir_sampling/reservoir_sampling.rs
extern crate rand; use rand::Rng; use std::io; fn select_random_k(arr: &Vec<i64>, k: u64) -> Vec<i64> { let mut reservoir: Vec<i64> = vec![]; // using variable length instead of k handles the case of when k > arr.len() let length: u64; if (arr.len() as u64) < k { length = arr.len() as u64; ...
code/randomized_algorithms/src/shuffle_an_array/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter Collaborative effort by [OpenGenus](https://github.com/opengenus)
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.cpp
#include <array> #include <iostream> #include <iterator> #include <random> // Part of Cosmos by OpenGenus Foundation template<class It, class RNG> void shuffle_an_array(It first, It last, RNG &&rng) { std::uniform_int_distribution<> dist; using ptype = std::uniform_int_distribution<>::param_type; using std...
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.java
// Part of Cosmos by OpenGenus Foundation import java.util.Random; import java.util.Arrays; public class Shuffle_An_Array { static void randomizing(int array[], int n) { Random r = new Random(); for(int i = n-1;i>0;i--) { int j = r.nextInt(i); int temp = array[i]; array[i] = array[j]; a...
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.js
// Part of Cosmos by OpenGenus Foundation // This is a JavaScript implementation of Fisher-Yates shuffle based on // [lodash/shuffle.js](https://github.com/lodash/lodash/blob/master/shuffle.js). // This use `crypto` module if possible to provide stronger pseudo randomness. const provideRandomSeed = (function() { if...
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.php
<?php # Part of Cosmos by OpenGenus Foundation trait ArrayRandomize { /** * Shuffle a given array * * @param array $entries * @return array */ public function shuffle(array $entries) : array { $length = count($entries); for ($i = ($length - 1); $i >= 0; $i--) { ...
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.py
# Python Program to shuffle a given array import random import time # Part of Cosmos by OpenGenus Foundation # A function to generate a random permutation of arr[] def randomize(arr): random.seed(time.time()) # seed the random generator # Start from the last element and swap one by one. We don't # need ...
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.rb
# Implementation of the algo # Stdlib has #shuffle, use that instead def randomize(arr, n) n -= 1 n.downto(1).each do |i| j = rand(i + 1) arr[i], arr[j] = arr[j], arr[i] end arr end p randomize([1, 2, 3], 3)
code/randomized_algorithms/src/shuffle_an_array/shuffle_an_array.rs
extern crate rand; use rand::Rng; fn swap(arr: &mut Vec<i64>, i: usize) { let a = &arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = *a; } fn randomize(arr: &Vec<i64>) -> Vec<i64> { let mut rng = rand::thread_rng(); let mut temp = arr.clone(); for i in 0..arr.len() - 1 { let random_num = rng.g...
code/randomized_algorithms/src/shuffle_an_array/shuffle_library.rb
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] a.shuffle
code/randomized_algorithms/test/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/search/src/README.md
# cosmos Your personal library of every algorithm and data structure code that you will ever encounter
code/search/src/binary_search/BinarySearch.asm
; Author: SYEED MOHD AMEEN ; Email: [email protected] ;----------------------------------------------------------------; ; Binary Searching Subroutine ; ;----------------------------------------------------------------; ;------------------------------------------------...
code/search/src/binary_search/README.md
# Binary search The binary search algorithm is used for finding an element in a sorted array. It has the average performance O(log n). ## Procedure 1. Find middle element of the array. 2. Compare the value of the middle element with the target value. 3. If they match, it is returned. 4. If the value is less or greate...
code/search/src/binary_search/binary_search.c
#include <stdio.h> /* * Part of Cosmos by OpenGenus Foundation */ // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 int recursiveBinarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; // If the...
code/search/src/binary_search/binary_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * binary search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace binary_search_impl * { * struct binary_search_tag {}; * struct recursive_binary_search_tag :public binary_search_tag {}; * struct itera...
code/search/src/binary_search/binary_search.cs
using System; namespace binary_search { class Program { static void Main(string[] args) { int[] arr = new int[10] {1, 10, 14, 26, 39, 44, 68, 77, 81, 92}; Console.WriteLine("Array: "); for(int i=0; i<10; i++) { Cons...
code/search/src/binary_search/binary_search.ex
defmodule Cosmos.Search.BinarySearch do def binary_search(array, key) do bs array, key, 0, length(array) end defp bs([], _, _, _), do: nil defp bs([_], _, _, _), do: 0 defp bs(_, _, min, max) when max < min, do: nil defp bs(array, key, min, max) do mid = div min + max, 2 {_, val} = Enum.fe...
code/search/src/binary_search/binary_search.go
package main import "fmt" import "sort" // Part of Cosmos by OpenGenus Foundation func binarySearch(data []int, value int) int { startIndex := 0 endIndex := len(data) - 1 for startIndex <= endIndex { midIndex := (startIndex + endIndex) / 2 mid := data[midIndex] if mid < value { endIndex = midIndex - 1 ...
code/search/src/binary_search/binary_search.hs
{- Part of Cosmos by OpenGenus Foundation -} binarySearch :: [Int] -> Int -> Int -> Int -> Int binarySearch arr val low high | high < low = -1 | arr!!mid < val = binarySearch arr val (mid+1) high | arr!!mid > val = binarySearch arr val low (mid-1) | otherwise = mid where mid = (low + h...
code/search/src/binary_search/binary_search.java
/* * Part of Cosmos by OpenGenus Foundation */ class Search {//Implementation of Binary Search in java static int recursiveBinarySearch(int arr[], int l, int r, int x) {//recursive function that returns the index of element x if it is present in arr[],else returns -1 if (r>=l) { int...
code/search/src/binary_search/binary_search.js
// implementation by looping function binarySearchLooping(array, key) { let lo = 0, hi = array.length - 1; while (lo <= hi) { let mid = Math.floor((lo + hi) / 2, 10); let element = array[mid]; if (element < key) { lo = mid + 1; } else if (element > key) { hi = mid - 1; } else { ...
code/search/src/binary_search/binary_search.kt
// Part of Cosmos by OpenGenus Foundation fun <T : Comparable<T>> binarySearch(a: Array<T>, key: T): Int? { var lowerBound = 0 var upperBound = a.size while (lowerBound < upperBound) { val middleIndex = lowerBound + (upperBound - lowerBound) / 2 when { a[middleIndex] == key -> r...
code/search/src/binary_search/binary_search.php
<?php /** * Part of Cosmos by OpenGenus Foundation * * @param array $array * @param int $low * @param int $high * @param int $search * * @return int */ function binarySearch(array $array, $low, $high, $search) { if ($high >= $low) { $middle = (int) ($low + ($high - $low) / 2); if ($a...
code/search/src/binary_search/binary_search.py
""" Part of Cosmos by OpenGenus Foundation """ def _binary_search_recursive_impl(arr, x, left, right): if right > left: mid = left + int((right - left) / 2) if arr[mid] == x: return mid elif arr[mid] > x: return _binary_search_recursive_impl(arr, x, left, mid - 1)...
code/search/src/binary_search/binary_search.rb
# Part of Cosmos by OpenGenus Foundation def binary_search(arr, l, r, x) return -1 if x.nil? if r >= l mid = (l + r) / 2 if arr[mid] == x mid elsif arr[mid] > x binary_search(arr, l, mid - 1, x) else binary_search(arr, mid + 1, r, x) end end end arr = [3, 5, 12, 56, 92, ...
code/search/src/binary_search/binary_search.rkt
#lang racket (define (binary-search val l) (cond [(empty? l) false] [(equal? val (first l)) true] [else (define midpoint (quotient (length l) 2)) (define value-at-midpoint (first (drop l midpoint))) (if (>= val value-at-midpoint) (binary-search val (drop l midpo...
code/search/src/binary_search/binary_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9]; let find_me = 5; let result = binary_search(&nums, find_me, 0, nums.len()); println!("Given Array: {:?}", nums); match result { Some(index) => println!("Searched for {} and found index {}.", find_me, index), None => println!("Searched for...
code/search/src/binary_search/binary_search.scala
package opengenus.cosmos.sorting import scala.annotation.tailrec object BinarySearch { trait SearchResult case class Found(i: Int) extends SearchResult case object NotFound extends SearchResult def apply[T](element: T)(collection: List[T])(implicit ord: Ordering[T]): SearchResult = { @tail...
code/search/src/binary_search/binary_search.sh
#!/bin/bash #read Limit echo Enter array limit read limit #read Elements echo Enter elements n=1 while [ $n -le $limit ] do read num eval arr$n=$num n=`expr $n + 1` done #read Search Key Element echo Enter key element read key low=1 high=$n found=0 #Find middle element #for(( low=0,found=0,high=$((n-1)) ; l<=u ; )...
code/search/src/binary_search/binary_search.swift
// binary_search.swift // Created by iraniya on 10/4/17. // Part of Cosmos by OpenGenus Foundation /** Binary Search Recursively splits the array in half until the value is found. If there is more than one occurrence of the search key in the array, then there is no guarantee which one it finds. Note: The...
code/search/src/binary_search/binary_search_2.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <cstdlib> #include <iostream> #include <algorithm> /* Utility functions */ void fill(std::vector<int> &v) { for (auto& elem : v) elem = rand() % 100; } void printArr(std::vector<int> &v) { for (const auto& elem : v) std:...
code/search/src/binary_search/binarysearchrecursion.cpp
#include <iostream> using namespace std; int BinarySearch(int arr[], int start, int end, int item){ if(start > end) return -1; int mid = start + (end-start)/2; if (arr[mid] == item) return mid; else if(arr[mid] < item) BinarySearch(arr, mid+1, end, item); else Bin...
code/search/src/exponential_search/README.md
# cosmos # Exponential Search Exponential search involves two steps: 1) Find range where element is present 2) Do Binary Search in above found range. # How to find the range where element may be present? The idea is to start with subarray size 1 compare its last element with x, then try size 2, then 4 and so on unt...
code/search/src/exponential_search/exponential_search.c
#include <stdio.h> int min(int a, int b) { return (a < b ? a : b); } int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; if (arr[mid] == x) return (mid); if (arr[mid] > x) return (binarySearch(arr, l, mid - 1, x)); ...
code/search/src/exponential_search/exponential_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * jump search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace exponenial_search_impl * { * template<typename _Random_Access_Iter, typename _Comp, * typename _Tp = typename std::iterator_trait...
code/search/src/exponential_search/exponential_search.cs
// C# program to find an element x in a sorted array using Exponential search. using System; // Part of Cosmos by OpenGenus Foundation class ExponentialSearch { // Returns position of first ocurrence of x in array static int exponentialSearch(int[] arr, int n, int x) { // If x is present at firt...
code/search/src/exponential_search/exponential_search.go
package main import ( "fmt" ) func binarySearch(data []int, left int, right int, value int) int { if right >= left { mid := left + (right-left)/2 if data[mid] == value { return mid } if data[mid] > value { return binarySearch(data, left, mid-1, value) } return binarySearch(data, mid+1, right, valu...
code/search/src/exponential_search/exponential_search.java
// Java program to find an element x in a sorted array using Exponential search. import java.util.Arrays; // Part of Cosmos by OpenGenus Foundation class ExponentialSearch { // Returns position of first ocurrence of x in array static int exponentialSearch(int arr[], int n, int x) { // If x is pr...
code/search/src/exponential_search/exponential_search.js
/* Part of Cosmos by OpenGenus Foundation */ /* Program to find an element in a sorted array using Exponential search. */ function binarySearch(arr, left, right, element) { if (right >= left) { const mid = left + Math.floor((right - left) / 2); if (arr[mid] == element) { return mid; } else if (arr...
code/search/src/exponential_search/exponential_search.php
<?php $dontPrintBinarySearchTest = true; require_once '../binary_search/binary_search.php'; /** * Part of Cosmos by OpenGenus Foundation * * @param array $array * @param int $search * * @return int */ function exponentialSearch(array $array, $search) { if (($count = count($array)) === 0) { return...
code/search/src/exponential_search/exponential_search.py
""" Part of Cosmos by OpenGenus Foundation """ def _binary_search(arr, element, left, right): if right > left: mid = (left + right) >> 1 if arr[mid] == element: return mid elif arr[mid] > element: return _binary_search(arr, element, left, mid - 1) else: ...
code/search/src/exponential_search/exponential_search.rb
def binary_search(arr, l, r, x) return -1 if x.nil? if r >= l mid = (l + r) / 2 if arr[mid] == x mid elsif arr[mid] > x binary_search(arr, l, mid - 1, x) else binary_search(arr, mid + 1, r, x) end end end def exponential_search(arr, element) return 0 if arr[0] == element ...
code/search/src/exponential_search/exponential_search.rs
fn main() { let nums = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]; let find_me = 13; let index = exponential_search(&nums, find_me); println!("Given Array: {:?}\n", nums); println!("Searched for {} and found index {}", find_me, index); } fn exponential_search(nums: &Vec<i64>, search_value: i64) -> i...
code/search/src/exponential_search/exponential_search2.cpp
// C++ program to find an element x in a // sorted array using Exponential search. #include <cstdio> #define min(a, b) ((a) < (b) ? (a) : (b)) using namespace std; int binarySearch(int arr[], int, int, int); // Returns position of first ocurrence of // x in array int exponentialSearch(int arr[], int n, int x) { /...
code/search/src/fibonacci_search/fibonacci_search.c
// search | fibonacci search | c // Part of Cosmos by OpenGenus Foundation /* ar -> Array name n -> Array size secondPreceding -> Number at second precedence firstPreceding -> Number at first precedence nextNum -> Fibonacci Number equal to or first greatest than the array size range -> Eleminated range marker */ #in...
code/search/src/fibonacci_search/fibonacci_search.cpp
/* * Part of Cosmos by OpenGenus Foundation * * fibonacci search synopsis * * warning: in order to follow the convention of STL, the interface is [begin, end) !!! * * namespace fibonacci_search_impl * { * template<typename _Input_Iter, * typename _Tp = typename std::iterator_traits<_Input_Iter>::valu...
code/search/src/fibonacci_search/fibonacci_search.java
// search | fibonacci search | c // Part of Cosmos by OpenGenus Foundation /** * Fibonacci Search is a popular algorithm which finds the position of a target value in * a sorted array * * The time complexity for this search algorithm is O(log3(n)) * The space complexity for this search algorithm is O(1) */ public ...
code/search/src/fibonacci_search/fibonacci_search.js
function fibonacciSearch(ar, x, n) { var secondPreceding = 0, firstPreceding = 1; var nextNum = secondPreceding + firstPreceding; while (nextNum < n) { secondPreceding = firstPreceding; firstPreceding = nextNum; nextNum = secondPreceding + firstPreceding; } var range = -1; while (nextNum ...