filename
stringlengths 7
140
| content
stringlengths 0
76.7M
|
---|---|
code/search/src/fibonacci_search/fibonacci_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
def fibonacci_search(arr, x):
length = len(arr)
fib_m2 = 0
fib_m1 = 1
fib_m = fib_m2 + fib_m1
while fib_m < length:
fib_m2 = fib_m1
fib_m1 = fib_m
fib_m = fib_m2 + fib_m1
offset = -1
while fib_m > 1:
i = min(offset + fib_m2, length - 1)
if arr[i] < x:
fib_m = fib_m1
fib_m1 = fib_m2
fib_m2 = fib_m - fib_m1
offset = i
elif arr[i] > x:
fib_m = fib_m2
fib_m1 = fib_m1 - fib_m2
fib_m2 = fib_m - fib_m1
else:
return i
if fib_m1 and offset < length - 1 and arr[offset + 1] == x:
return offset + 1
return -1
|
code/search/src/fibonacci_search/fibonacci_search.swift | /* Part of Cosmos by OpenGenus Foundation */
// fibonacci_search.swift
// Created by erwolfe on 11/17/2017
/**
Fibonacci Search looks through an array for an element and returns it if its found otherwise -1 is returned.
- parameters:
- numberArray: An array of ints that is being traversed to find an element.
- x: An int that is been looked for in the array.
- n: The size of the of the array.
- returns:
An int that is the index of the element in the array unless its not found and then -1 is returned.
*/
func fibonacciSearch(_ numberArray: [Int], _ x: Int, _ n: Int) -> Int {
var fibM2 = 0 //(m-2)'th Fibonacci number
var fibM1 = 1 //(m-1)'th Fibonacci number
var fibM = fibM2 + fibM1 //m'th Fibonacci
// Gets the smallest fibonacci number greater than or equal to n
while(fibM < n){
fibM2 = fibM1
fibM1 = fibM
fibM = fibM2 + fibM1
}
// Set offset to -1
var offset = -1
// Continue looping until the index of element in the array is found
while(fibM > 1){
let i = minimumNumber(offset+fibM2, n-1)
if numberArray[i] < x {
fibM = fibM1
fibM1 = fibM2
fibM2 = fibM - fibM1
offset = i
} else if numberArray[i] > x {
fibM = fibM2
fibM1 = fibM1 - fibM2
fibM2 = fibM - fibM1
} else {
return i
}
}
// If the element is found then return the offset plus 1
if fibM1 == 1 && numberArray[offset+1] == x {
return offset + 1
}
// If the element x is not found then return -1
return -1
}
/**
Utility function that returns the minimum number between two ints.
- parameters:
- x: An int to check to see if it's the minimum number.
- y: An int to check to see if it's the minimum number.
- returns:
An int that is the minimum number between the two ints.
*/
private func minimumNumber(_ x: Int, _ y: Int) -> Int {
return x <= y ? x : y
}
|
code/search/src/fuzzy_search/fuzzy_search.js | //
// A node module that executes the Fuzzy Search algorithm
//
// Usage:
// const fs = require('./fuzzySearch');
// console.log(fs('A', 'ACC'))
//
"use strict";
function fuzzySearch(needle, haystack) {
var haystack_length = haystack.length;
var needle_length = needle.length;
if (needle_length > haystack_length) {
return false; // return false if Needle is longer than haystack
}
if (needle_length === haystack_length) {
return needle === haystack;
}
mainLoop: for (var i = 0, j = 0; i < needle_length; i++) {
var nth_character = needle.charCodeAt(i);
while (j < haystack_length) {
if (haystack.charCodeAt(j++) === nth_character) {
continue mainLoop;
}
}
return false;
}
return true;
}
module.exports = fuzzysearch;
|
code/search/src/fuzzy_search/fuzzy_search.php | <?php
/* Part of Cosmos by OpenGenus Foundation */
/* Usage:
echo (fuzzySearch('B', 'ACC')) ? 'true' : 'false';
*/
function fuzzySearch($needle, $haystack)
{
if (strlen($needle) > strlen($haystack)) {
return false;
}
if (strlen($needle) === strlen($haystack)) {
return $needle === $haystack;
}
for ($i = 0; $i < strlen($needle); $i++) {
$nth_character = substr($needle, $i, 1);
foreach (str_split($haystack) as $char) {
if($char === $nth_character) {
return true;
}
}
return false;
}
}
|
code/search/src/interpolation_search/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/src/interpolation_search/interpolation_search.c | #include <stdio.h>
// Part of Cosmos by OpenGenus Foundation
int interpolationSearch(int* array, int n, int key){
int high = n-1;
int low = 0;
int mid;
while ( (array[high] != array[low]) && (key >= array[low]) && (key <= array[high])) {
mid = low + (int)( ((float)(high-low) / (array[high] - array[low])) * (key - array[low]) );
if(array[mid] == key)
return mid;
else if (array[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
void test(){
// Array of items on which search will be conducted.
int array[10] = {1, 5, 9, 12, 16, 18, 25, 56, 76, 78};
int n = sizeof(array)/sizeof(array[0]);
// Element to be searched
int key = 25;
int index = interpolationSearch(array, n, key);
if(index !=-1)
printf("Element found at index %d\n", index);
else
printf("EElement not found.\n");
}
int main() {
test(25);
return 0;
}
|
code/search/src/interpolation_search/interpolation_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* interpolation search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* // [begin, end)
* template<typename _Random_Access_Iter,
* typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Compare>
* _Random_Access_Iter
* interpolationSearch(_Random_Access_Iter begin,
* _Random_Access_Iter end,
* _Type const &find,
* _Compare compare);
*
* // [begin, end)
* template<typename _Random_Access_Iter,
* typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type>
* _Random_Access_Iter
* interpolationSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Type const &find);
*/
#include <functional>
// [begin, end)
template<typename _Random_Access_Iter,
typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Compare>
_Random_Access_Iter
interpolationSearch(_Random_Access_Iter begin,
_Random_Access_Iter end,
_Type const &find,
_Compare compare)
{
auto notFound = end;
if (begin != end)
{
--end;
// TODO: replace '<=' with '!=' or else to be more useful,
// (e.g., allow input iterator can be passed)
while (begin <= end)
{
// Now we will enquire the position keeping in mind the uniform distribution in mind
auto pos = begin;
if (compare(*begin, *end))
{
auto len = std::distance(begin, end) * (find - *begin) / (*end - *begin);
std::advance(pos, len);
}
if (pos < begin || pos > end)
break;
else if (compare(*pos, find))
begin = ++pos;
else if (compare(find, *pos))
end = --pos;
else
return pos;
}
}
return notFound;
}
// [begin, end)
template<typename _Random_Access_Iter,
typename _Type = typename std::iterator_traits<_Random_Access_Iter>::value_type>
_Random_Access_Iter
interpolationSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Type const &find)
{
return interpolationSearch(begin, end, find, std::less<_Type>());
}
|
code/search/src/interpolation_search/interpolation_search.go | package main
import "fmt"
func interpolationSearch(array []int, key int) int {
min, max := array[0], array[len(array)-1]
low, high := 0, len(array)-1
for {
if key < min {
return low
}
if key > max {
return high + 1
}
var guess int
if high == low {
guess = high
} else {
size := high - low
offset := int(float64(size-1) * (float64(key-min) / float64(max-min)))
guess = low + offset
}
if array[guess] == key {
for guess > 0 && array[guess-1] == key {
guess--
}
return guess
}
if array[guess] > key {
high = guess - 1
max = array[high]
} else {
low = guess + 1
min = array[low]
}
}
}
func main() {
items := []int{1, 2, 9, 20, 31, 45, 63, 70, 100}
fmt.Println(interpolationSearch(items, 63))
}
|
code/search/src/interpolation_search/interpolation_search.java |
public class Interpolation {
static int arr[] = new int[]{10, 12, 13, 15, 17, 19, 20, 21, 22, 23,
24, 33, 35, 42, 49};
public static int interpolationSearch(int x)
{
// Find indexes of two corners
int lo = 0, hi = (arr.length - 1);
// Since array is sorted, an element present
// in array must be in range defined by corner
while (lo <= hi && x >= arr[lo] && x <= arr[hi])
{
int pos = lo + (((hi-lo) /
(arr[hi]-arr[lo]))*(x - arr[lo]));
if (arr[pos] == x)
return pos;
if (arr[pos] < x)
lo = pos + 1;
else
hi = pos - 1;
}
return -1;
}
public static void main(String[] args)
{
int x = 20;
int index = interpolationSearch(x);
// If element was found
if (index != -1)
System.out.println("Element found at index " + index);
else
System.out.println("Element not found.");
}
}
|
code/search/src/interpolation_search/interpolation_search.js | // implementation with looping
function interpolationSearchRecursion(
arr,
value,
low = 0,
high = arr.length - 1
) {
if (arr.length === 0 || (arr.length === 1 && arr[0] !== value)) {
return -1;
}
let mid =
low +
parseInt(((value - arr[low]) / (arr[high] - arr[low])) * (arr.length - 1));
if (mid < 0 || mid >= arr.length) {
return -1;
}
if (arr[mid] === value) {
return mid;
} else if (arr[mid] > value) {
return interpolationSearchRecursion(arr, value, low, mid - 1);
} else {
return interpolationSearchRecursion(arr, value, mid + 1, high);
}
}
// implementation with recursion
function interpolationSearchLooping(arr, value) {
let low = 0,
high = arr.length - 1;
while (low < high) {
let mid = parseInt(
((value - arr[low]) / (arr[high] - arr[low])) * (arr.length - 1)
);
if (arr[mid] === value) {
return mid;
} else if (arr[mid] > value) {
high = mid - 1;
} else {
low = mid + 1;
}
}
if (arr[low] === value) {
return low;
} else {
return -1;
}
}
// test case
const a = [0, 1, 2, 3, 3, 4, 6, 7, 7, 8, 9];
interpolationSearchRecursion(a, 7);
interpolationSearchRecursion(a, 9);
interpolationSearchRecursion(a, -2);
interpolationSearchLooping(a, 7);
interpolationSearchLooping(a, 9);
interpolationSearchLooping(a, -2);
|
code/search/src/interpolation_search/interpolation_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function interpolationSearch(array $array, $search)
{
list ($low, $high) = [0, count($array) - 1];
while (($array[$high] !== $array[$low]) && ($search >= $array[$low]) && ($search <= $array[$high])) {
$middle = $low + (($search - $array[$low]) * ($high - $low) / ($array[$high] - $array[$low]));
if ($array[$middle] < $search) {
$low = $middle + 1;
} else if ($search < $array[$middle]) {
$high = $middle - 1;
} else {
return $middle;
}
}
return $search === $array[$low] ? $low : -1;
}
echo sprintf("Position of %d is %d\n", $search = 33, interpolationSearch($array = [7, 11, 13, 33, 66], $search));
|
code/search/src/interpolation_search/interpolation_search.py | def interpolation_search(arr, x):
lo = 0
hi = len(arr) - 1
while lo <= hi and x >= arr[lo] and x <= arr[hi]:
m = lo + int(float(hi - lo) / (arr[hi] - arr[lo] + 1) * (x - arr[lo]))
if arr[m] == x:
return m
if arr[m] < x:
lo = m + 1
else:
hi = m - 1
return -1
|
code/search/src/jump_search/README.md | # Cosmos

# Jump Search
Jump Search is a searching algorithm for sorted arrays. The idea is to skip some elements by jumping head in the array. In order of time complexity: Linear Search O(n) < Jump Search O(√n) < Binary Search O(Log n). However, Jump Search has an advantage over Binary search in that you will only ever traverse backwards one time.
## Procedure
1. Set the step length to be equal to the √n, and the previous to be the 0th index
2. Compare the value of the step element with the target value.
3. If they match, it is returned.
4. If the step value is less than the target value, set previous to be to be current step, jump again.
5. If the step value is greater than the target value, reverse linear search until value is found, or until previous is reached.
[Jump Search Wikipedia](https://en.wikipedia.org/wiki/Jump_search)
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/search/src/jump_search/jump_search.c | #include <stdio.h>
#include <math.h>
#define MAX 100
int find_element(int element);
int arr[MAX],n;
int main()
{
int i,element,result;
printf("\nEnter the number of elements: ");
scanf("%d",&n);
printf("\nEnter the elements of array: \n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}
printf("\n\nEnter the element you want to search: ");
scanf("%d",&element);
result=find_element(element);
if(result==-1)
{
printf("\nElement is not found in the array !\n");
}
else
{
printf("\nElement %d is present at position %d",element,result);
}
return 0;
}
int find_element(int element)
{
int jump_step,prev=0;
jump_step=floor(sqrt(n));
/* Finding block in which element lies, if it is present */
while(arr[prev]<element)
{
if(arr[jump_step]>element || jump_step>=n)
{
break;
}
else
{
prev=jump_step;
jump_step=jump_step+floor(sqrt(n));
}
}
/*Finding the element in the identified block */
while(arr[prev]<element)
{
prev++;
}
if(arr[prev]==element)
{
return prev+1;
}
else
{
return -1;
}
}
|
code/search/src/jump_search/jump_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 jump_search_impl
* {
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Compare>
* _Random_Access_Iter
* jumpSearchImpl(_Random_Access_Iter begin,
* _Random_Access_Iter end,
* _Tp const &find,
* _Compare comp,
* std::random_access_iterator_tag);
* } // jump_search_impl
*
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
* typename _Compare>
* _Random_Access_Iter
* jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp);
*
* template<typename _Random_Access_Iter,
* typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
* _Random_Access_Iter
* jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find);
*/
#include <functional>
#include <cmath>
namespace jump_search_impl
{
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Compare>
_Random_Access_Iter
jumpSearchImpl(_Random_Access_Iter begin,
_Random_Access_Iter end,
_Tp const &find,
_Compare comp,
std::random_access_iterator_tag)
{
if (begin != end)
{
auto dist = std::distance(begin, end);
auto sqrtDist = static_cast<size_t>(std::sqrt(dist));
auto curr = begin;
// 1. Finding the block where element is
while (curr < end && comp(*curr, find))
std::advance(curr, sqrtDist);
if (curr != begin)
std::advance(curr, -sqrtDist);
// 2. Doing a linear search for find in block
while (curr < end && sqrtDist-- > 0 && comp(*curr, find))
std::advance(curr, 1);
// 3. If element is found
if (!comp(*curr, find) && !comp(find, *curr))
return curr;
}
return end;
}
} // jump_search_impl
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type,
typename _Compare>
_Random_Access_Iter
jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find, _Compare comp)
{
auto category = typename std::iterator_traits<_Random_Access_Iter>::iterator_category();
return jump_search_impl::jumpSearchImpl(begin, end, find, comp, category);
}
template<typename _Random_Access_Iter,
typename _Tp = typename std::iterator_traits<_Random_Access_Iter>::value_type>
_Random_Access_Iter
jumpSearch(_Random_Access_Iter begin, _Random_Access_Iter end, _Tp const &find)
{
return jumpSearch(begin, end, find, std::less<_Tp>());
}
|
code/search/src/jump_search/jump_search.go | package main
import (
"fmt"
"math"
)
// Part of Cosmos by OpenGenus Foundation
func jumpSearch(arr []int, x int) int {
var left, right int
length := len(arr)
jump := int(math.Sqrt(float64(length)))
for left < length && arr[left] <= x {
right = min(length-1, left+jump)
if arr[left] <= x && arr[right] >= x {
break
}
left += jump
}
if left >= length || arr[left] > x {
return -1
}
right = min(length-1, right)
tempIndex := left
for tempIndex <= right && arr[tempIndex] <= x {
if arr[tempIndex] == x {
return tempIndex
}
tempIndex++
}
return -1
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func resultPrint(element, index int) {
if index < 0 {
fmt.Printf("The element %d was not found\n", element)
} else {
fmt.Printf("The element %d is at index %d \n", element, index)
}
}
func main() {
values := []int{1, 2, 3, 4, 5, 12, 30, 35, 46, 84}
resultPrint(5, jumpSearch(values, 5))
resultPrint(7, jumpSearch(values, 7))
}
|
code/search/src/jump_search/jump_search.java |
public class JumpSearch {
// Java program to implement Jump Search.
public static int SearchJump(int[] arr, int x) {
int n = arr.length;
// block size through which jumps take place
int step = (int) Math.floor(Math.sqrt(n));
// search in the block
int prev = 0;
while (arr[Math.min(step, n) - 1] < x) {
prev = step;
step += (int) Math.floor(Math.sqrt(n));
if (prev >= n)
return -1;
}
// Doing a linear search for x in block
while (arr[prev] < x) {
prev++;
/*
* If we reached next block or end of array, element is not present.
*/
if (prev == Math.min(step, n))
return -1;
}
// If element is found
if (arr[prev] == x)
return prev;
// element not found
return -1;
}
// Driver program to test function
public static void main(String[] args) {
int arr[] = { 0, 1, 1, 2, 3, 5, 9, 13, 21, 34, 55, 89, 145, 237, 377, 610 };
int x = 55;
// Find the index of 'x' using Jump Search
int index = SearchJump(arr, x);
// Print the index where 'x' is located
if (x != -1)
System.out.println("Number " + x + " is found at index " + index);
else {
System.out.println("Number " + x + " not found");
}
}
}
|
code/search/src/jump_search/jump_search.js | let array = [0, 1, 2, 5, 10, 15, 20, 25, 30, 33];
let wanted = 2;
pos = jumpSearch(array, wanted);
if (pos == -1) {
console.log("Value not found");
} else {
console.log(`Value ${wanted} on position ${pos}`);
}
function jumpSearch(array, wanted) {
const arrayLength = array.length;
const block = getValueBlockSearch(arrayLength);
const foundBlock = findBlockWithWanted(array, arrayLength, wanted, block);
return findValueInBlock(array, arrayLength, foundBlock, wanted, block);
}
function findBlockWithWanted(array, arrayLength, wanted, block) {
let step = block;
let prevStep = 0;
while (array[getStepPosition(step, arrayLength)] < wanted) {
prevStep = step;
step += block;
if (prevStep >= arrayLength) {
return -1;
}
}
return prevStep;
}
function findValueInBlock(array, arrayLength, prevStep, wanted, block) {
if (prevStep == -1) {
return prevStep;
}
while (array[prevStep] < wanted) {
prevStep += 1;
if (prevStep == Math.min(block, arrayLength)) {
return -1;
}
}
if (array[prevStep] == wanted) {
return prevStep;
}
return -1;
}
function getStepPosition(step, arrayLength) {
return Math.min(step, arrayLength) - 1;
}
function getValueBlockSearch(length) {
return Math.floor(Math.sqrt(length));
}
|
code/search/src/jump_search/jump_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function jumpSearch(array $array, $search)
{
list ($count, $step, $previous) = [$count = count($array), (int) sqrt($count), 0];
while ($array[min($step, $count) - 1] < $search) {
$previous = $step;
$step += (int) sqrt($count);
if ($previous >= $count) {
return -1;
}
}
while ($array[$previous] < $search) {
$previous++;
if ($previous === min($step, $count)) {
return -1;
}
}
return $array[$previous] === $search ? $previous : -1;
}
echo sprintf("Position of %d is %d\n", $search = 33, jumpSearch($array = [7, 11, 13, 33, 66], $search));
|
code/search/src/jump_search/jump_search.py | """
Part of Cosmos by OpenGenus Foundation
"""
import math
def jump_search(arr, x):
n = len(arr)
jump = int(math.sqrt(n))
left, right = 0, 0
while left < n and arr[left] <= x:
right = min(n - 1, left + jump)
if arr[left] <= x and arr[right] >= x:
break
left += jump
if left >= n or arr[left] > x:
return -1
right = min(n - 1, right)
temp = left
while temp <= right and arr[temp] <= x:
if arr[temp] == x:
return temp
temp += 1
return -1
|
code/search/src/jump_search/jump_search.rs | // Part of Cosmos by OpenGenus Foundation
use std::cmp::min;
fn jump_search(arr: Vec<i32>,n :i32) -> i32 {
let mut step = (arr.len() as f64).sqrt() as usize;
let len = arr.len();
let mut prev: usize = 0;
//Jumps
while arr[min(step, len)-1] < n {
prev = step;
step += step;
if prev >= len {
return -1
}
}
// Linear search
while arr[prev] < n {
prev += 1 ;
if arr[prev] == (min(step, len)) as i32 {
return -1
}
}
// Element found
if arr[prev] == n {
return prev as i32
}
-1
}
fn main() {
let arr = vec![0, 1, 1, 2, 3, 5, 8, 13, 21,34, 55, 89, 144, 233, 377, 610];
println!("Found {} at index {}",55,jump_search(arr,55));
} |
code/search/src/jump_search/jump_search.swift | import Foundation
func jumpSearch<T: Comparable>(_ a: [T], for key: T) -> Int? {
let count = a.count
var step = Int(sqrt(Double(count)))
var previous = 0
while a[min(step, count) - 1] < key {
previous = step
step += Int(sqrt(Double(count)))
if previous >= count {
return nil
}
}
while a[previous] < key {
previous += 1
if previous == min(step, count) {
return nil
}
}
return a[previous] == key ? previous : nil
}
if let position = jumpSearch([7, 11, 13, 33, 66], for: 33) {
print("Found 33 in [7, 11, 13, 33, 66] at position \(position)")
} else {
print("Can't find 33 in [7, 11, 13, 33, 66]")
}
|
code/search/src/linear_search/LINEAR_SEARCH.ASM | ; Author: SYEED MOHD AMEEN
; Email: [email protected]
;----------------------------------------------------------------;
; LINEAR SEARCH SUBROUTINE ;
;----------------------------------------------------------------;
;----------------------------------------------------------------;
; FUNCTION PARAMETERS ;
;----------------------------------------------------------------;
; 1. push KEY element ;
; 2. push no. of element in Array ;
; 3. push base address of Array ;
;----------------------------------------------------------------;
LINSEARCH:
POP AX
POP SI ;BASE ADDRESS OF ARRAY
POP CX ;COUNTER REGISTER
POP DX ;KEY ELEMENT
PUSH AX
REPEAT_LINSEARCH:
CMP DH,[SI] ;COMPARE KEY == [SI]
JNE NOTFOUND
POP AX ;IF ELEMENT FOUND RETURN ADDRESS
PUSH SI
PUSH AX
RET ;RETURN SUBROUTINE
NOTFOUND:
INC SI
LOOP REPEAT_LINSEARCH
POP AX ;IF SEARCH UNSUCESSFUL RETURN 0X0000
MOV CX,0X0000
PUSH CX
PUSH AX
RET
|
code/search/src/linear_search/README.md | # Linear search
The linear search is the simplest of the searching algorithms.
The goal of the algorithm is check for existence of an element in the given array.
# How it works
Linear search goes through each element of the given array until either the element to be searched is found or we have reached the end of the array.
# Complexity
Time Complexity -> **O(n)**
Space Complexity -> **O(1)**
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/search/src/linear_search/linear_search.c | #include <stdio.h>
/*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Input: an integer array with size in index 0, the element to be searched
* Output: if found, returns the index of the element else -1
*/
int search(int arr[], int size, int x)
{
int i=0;
for (i=0; i<size; i++)
if (arr[i] == x)
return i;
return -1;
}
int main()
{
int arr[] = {2,3,1,5}; // Index 0 stores the size of the array (initially 0)
int size = sizeof(arr)/sizeof(arr[0]);
int find = 1;
printf("Position of %d is %d\n", find, search(arr,size,find));
return 0;
}
|
code/search/src/linear_search/linear_search.clj | ; generally in list processing languages we
; we don't work with indices but just in case
; you wanted to find position of element from list head
(defn linear-search-list
"Returns the position of the list element from head"
([tlist elem] ;tlist is a linked list
(linear-search tlist elem 0))
([[x remm] elem idx]
(if (= x elem)
idx
(recur remm elem (inc idx))))) ;recursive call with remaining list & args
(defn linear-search-in-vec
"Function takes persistent vector and searches for elem"
([tvec elem]
(linear-search-in-vec tvec elem idx))
([tvec elem idx]
(if (= elem (get tvec idx))
idx
(recur tvec elem (inc idx)))))
;Example usage
(linear-search (list 1 2 3 4 5) 4)
(linear-search-in-vec (vector 1 2 3 4 5 6) 4) |
code/search/src/linear_search/linear_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* linear search synopsis
*
* warning: in order to follow the convention of STL, the interface is [begin, end) !!!
*
* namespace linear_search_impl
* {
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
* _Input_Iter
* linearSearchImpl(_Input_Iter begin,
* _Input_Iter end,
* _Tp const &find,
* _Compare comp,
* std::input_iterator_tag);
* } // linear_search_impl
*
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
* _Input_Iter
* linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp);
*
* template<typename _Input_Iter,
* typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type>
* _Input_Iter
* linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find);
*/
#include <functional>
namespace linear_search_impl
{
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type,
typename _Compare>
_Input_Iter
linearSearchImpl(_Input_Iter begin,
_Input_Iter end,
_Tp const &find,
_Compare comp,
std::input_iterator_tag)
{
_Input_Iter current = begin;
while (current != end)
{
if (comp(*current, find))
break;
++current;
}
return current;
}
} // linear_search_impl
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type, typename _Compare>
_Input_Iter
linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find, _Compare comp)
{
auto category = typename std::iterator_traits<_Input_Iter>::iterator_category();
return linear_search_impl::linearSearchImpl(begin, end, find, comp, category);
}
template<typename _Input_Iter,
typename _Tp = typename std::iterator_traits<_Input_Iter>::value_type>
_Input_Iter
linearSearch(_Input_Iter begin, _Input_Iter end, _Tp const &find)
{
return linearSearch(begin, end, find, std::equal_to<_Tp>());
}
|
code/search/src/linear_search/linear_search.cs | // Part of Cosmos by OpenGenus
public class LinearSearch
{
public static void Main(string[] args)
{
int[] items = new int[] { 10, 12, 52, 634, 24, 743, 234, 7, 25, 742, 76, 25};
int itemToFind = 634;
int itemIndex = linearSearch(items, itemToFind);
if(itemIndex != -1)
System.Console.WriteLine(itemToFind + " found at " + itemIndex);
else
System.Console.WriteLine(itemToFind + " not found!");
}
public static int linearSearch(int[] items, int itemToFind)
{
for(int i = 0; i < items.Length; i++)
{
if(items[i] == itemToFind)
{
return i;
}
}
return -1;
}
} |
code/search/src/linear_search/linear_search.go | package main
import (
"fmt"
)
func main() {
arr := []int{1, 3, 45, 56, 8, 21, 7, 69, 12}
find := 56
index := search(arr, find)
if index != -1 {
fmt.Printf("%d found at index %d", find, index)
} else {
fmt.Printf("%d not found!", find)
}
}
func search(arr []int, x int) int {
for i, n := range arr {
if n == x {
return i
}
}
return -1
}
|
code/search/src/linear_search/linear_search.hs | linearsearch :: (Eq a) => [a] -> a -> Maybe Int
linearsearch [] _ = Nothing
linearsearch (x:xs) y = if x == y then Just 0 else (1 +) <$> linearsearch xs y
|
code/search/src/linear_search/linear_search.java | /*
* Part of Cosmos by OpenGenus Foundation
*
*/
// A possible (imaginary) package.
package org.opengenus.cosmos.search;
import java.util.Scanner;
/**
* The {@code LinearSearch} class is the simplest of the searching
* algorithm. The goal of the algorithm is to check the existence of an
* element in the given array.
* <p>
* <b>How it works</b>
* {@code LinearSearch} goes through each element of the given array until
* either the element to be searched is found or we have reached the end
* of the array.
* <p>
* <b>Complexity</b>
* Time Complexity -> O(n)
* Space Complexity -> O(1)
*
* @author Cosmos by OpenGenus Foundation
*
*/
class LinearSearch {
/**
* Searches for key in the given array. Returns the index within this
* array that is the element searched for.
*
* @param arr
* Array that is the source of the search.
*
* @param key
* The number to be searched for in the array.
*
* @return the index of the element, else -1.
*/
static int linearSearch(int arr[], int key) {
for (int i = 0; i < arr.length; i++) {
if (arr[i] == key)
return i;
}
return -1;
}
/**
* A recursive implementation of {@link #linearSearch()}
*
* @param arr
* Array that is the source of the search.
*
* @param key
* The number to be searched for in the array.
*
* @return A recursive call to {@link #recursiveLinearSearch()}
*/
static int recursiveLinearSearch(int arr[], int key) {
return recursiveLinearSearch(arr, key, 0);
}
private static int recursiveLinearSearch(int arr[], int key, int index) {
// Key not found at all.
if (index == arr.length)
return -1;
// Key found at current index.
if (key == arr[index])
return index;
// Else, keep moving through indices
return recursiveLinearSearch(arr, key, index + 1);
}
public static void main(String args[]) {
// Object of scanner class to take input.
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of the array to be searched");
int size = sc.nextInt();
int arr[] = new int[size];
// Loop to take input.
for(int i = 0; i < size; i++) {
System.out.println("Enter the element number " + (i + 1) + " of the array");
arr[i] = sc.nextInt();
}
System.out.println("Enter the number you want to find");
int key = sc.nextInt();
System.out.println("Position of " + key + " is " + linearSearch(arr, key));
System.out.println("Position of " + key + " is " + recursiveLinearSearch(arr, key));
}
}
|
code/search/src/linear_search/linear_search.js | /*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Input : An integer array and the element to be searched
* Output : If found returns the index of element or else -1
* Example :
* var index = linearSearch([1, 2, 3, 4, 7, 8], 8);
*
*/
function linearSearch(arr, element) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === element) {
return i;
}
}
return -1;
}
|
code/search/src/linear_search/linear_search.kt | // Part of Cosmos by OpenGenus Foundation
fun <T> linearSearch(array: Array<T>, key: T): Int? {
for (i in 0 until array.size) {
if (array[i] == key) {
return i
}
}
return null
}
fun main(args: Array<String>) {
val sample: Array<Int> = arrayOf(13, 17, 19, 23, 29, 31, 37, 41, 43)
val key = 23
val result = linearSearch(sample, key)
println(when (result) {
null -> "$key is not in sample"
else -> "Position of $key is $result"
})
} |
code/search/src/linear_search/linear_search.ml | (* Part of Cosmos by OpenGenus Foundation *)
let rec linear_search x = function
| [] -> -1
| hd :: tl when hd == x -> 0
| hd :: tl -> 1 + (linear_search x tl);;
|
code/search/src/linear_search/linear_search.nim | proc linear_search[T](collection: seq[T], item: T): T =
for i in 0..(collection.len() - 1):
if collection[i] == item:
return i
return -1
let s = @[42, 393, 273, 1239, 32]
echo linear_search(s, 273) # prints "2"
echo linear_search(s, 32) # prints "4"
echo linear_search(s, 1) # prints "-1"
|
code/search/src/linear_search/linear_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $search
*
* @return int
*/
function linearSearch(array $array, $search)
{
$count = count($array);
for ($i = 0; $i < $count; $i++) {
if ($array[$i] === $search) {
return $i;
}
}
return -1;
}
echo sprintf("Position of %d is %d\n", $search = 33, linearSearch($array = [7, 11, 13, 33, 66], $search));
|
code/search/src/linear_search/linear_search.py | def linear_search(arr, x):
for i in range(len(arr)):
if arr[i] == x:
return i
return -1
|
code/search/src/linear_search/linear_search.rb | # Part of Cosmos by OpenGenus Foundation
items = [5, 10, 34, 18, 6, 7, 45, 67]
target = 7
##
# Returns a boolean that indicates whether the target item is contained within
# the given list.
def linear_search(list, target)
# Iterate over each item in the list
list.each do |item|
return true if item == target
end
false
end
found = linear_search(items, target)
if found
puts "Found '#{target}'!"
else
puts "'#{target}' was not found."
end
|
code/search/src/linear_search/linear_search.re | let rec linearSearch = x =>
fun
| [] => (-1)
| [hd, ...tl] when hd === x => 0
| [hd, ...tl] => 1 + linearSearch(x, tl);
|
code/search/src/linear_search/linear_search.rs | fn search(vec: &[i32], n: i32) -> i32 {
for i in 0..vec.len() {
if vec[i] == n {
return i as i32; // Element found return index
}
}
return -1; // If element not found return -1
}
fn main() {
let arr = vec![1, 3, 45, 56, 8, 21, 7, 69, 12];
let num = 56;
let index = search(&arr, num);
if index != -1 {
println!("Found {}, at index {}", num, index);
}else {
println!("{} not found!", num)
}
} |
code/search/src/linear_search/linear_search.scala | /* Part of Cosmos by OpenGenus Foundation */
object LinearSearch extends App {
def linearSearch[A: Equiv](list: List[A], element: A): Option[Int] = {
list match {
case Nil => None
case head :: tail => if (head == element) Some(0) else (linearSearch(tail, element).map(_ + 1))
}
}
val list = (0 to 1000) map (_ => scala.util.Random.nextInt(1000))
val element = scala.util.Random.nextInt(1000)
val output = linearSearch(list.toList, element)
Console.println(s"Index: $output")
} |
code/search/src/linear_search/linear_search.swift | //
// linear_search.swift
// test
//
// Created by Kajornsak Peerapathananont on 10/14/2560 BE.
// Copyright © 2560 Kajornsak Peerapathananont. All rights reserved.
// Part of Cosmos by OpenGenus Foundation
import Foundation
/*
Input : array of item and the element that want to be search
Output : index of element (if found) or else -1
*/
func linear_search<T : Equatable>(array : [T], element : T) -> Int{
for (index, item) in array.enumerated() {
if(item == element){
return index
}
}
return -1
}
|
code/search/src/linear_search/sentinellinearsearch.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
/*
* Author: Visakh S
* Github: visakhsuku
* Input: The number of elements in an array, The element to be searched, An integer array.
* Output: if found returns "found" else "not found", using the sentinel linear search algorithm.
*/
#include <iostream>
#include <vector>
using namespace std;
void sentinelLinearSearch(std::vector<int> v, int n, int x)
{
int last, i = 0;
last = v[n - 1];
v[n - 1] = x;
while (v[i] != x)
i++;
if (i < n - 1 || last == x)
cout << "found";
else
cout << "not found";
}
int main()
{
ios_base::sync_with_stdio(false); cin.tie(NULL);
int n, x, input;
std::vector<int> v;
cin >> n >> x;
for (int i = 0; i < n; ++i)
{
cin >> input;
v.push_back(input);
}
sentinelLinearSearch(v, n, x);
return 0;
}
|
code/search/src/ternary_search/README.md | # Ternary search
The ternary search algorithm is used for finding a given element in a sorted array.
## Procedure
1. Find where the array divides into two thirds
2. Compare the value of both the thirds elements with the target element.
3. If they match, it is returned the index.
4. If the value is less than the first third, the search continues in the leftmost third of the array.
5. If the value is greater than the second third, the search continues in the rightmost third of the array.
6. If the value is both greater than the first third and less than the second third, the search continues in the middle third of the array.
5. The same procedure as in step 2-6 continues, but with a part of the array. This continues until the given element is found or until there are no elements left.
Collaborative effort by [OpenGenus](https://github.com/OpenGenus)
|
code/search/src/ternary_search/ternary_search.c | #include <stdio.h>
// Function to perform Ternary Search
int ternarySearch(int array[], int left, int right, int x)
{
if (right >= left) {
// Find the leftmid and rightmid
int intvl = (right - left) / 3;
int leftmid = left + intvl;
int rightmid = leftmid + intvl;
// Check if element is present at any mid
if (array[leftmid] == x)
return leftmid;
if (array[rightmid] == x)
return rightmid;
// As the element is not present at mid, then check on which side it is present
//Repeat the search operation on the side where it is present
if (x < array[leftmid]) {
//The element lies between left and leftmid
return ternarySearch(array, left, leftmid, x);
}
else if (x > array[leftmid] && x < array[rightmid]) {
//The element lies between leftmid and rightmid
return ternarySearch(array, leftmid, rightmid, x);
}
else {
//The element lies between rightmid and right
return ternarySearch(array, rightmid, right, x);
}
}
//Element not found
return -1;
}
//Main function
int main(void)
{
int array[] = {1, 2, 3, 5};
int size = sizeof(array)/ sizeof(array[0]);
int find = 3;
printf("Position of %d is %d\n", find, ternarySearch(array, 0, size-1, find));
return 0;
}
|
code/search/src/ternary_search/ternary_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* Ternary Search Uses Divide And Conquer Technique
*
* ternary search synopsis
*
* namespace ternary_search_impl
* {
* template<typename _RandomAccessIter,
* typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type,
* typename _Less>
* _RandomAccessIter
* ternarySearchImpl(_RandomAccessIter first,
* _RandomAccessIter last,
* const _RandomAccessIter ¬FoundSentinel,
* const _ValueType &find,
* _Less less);
* } // ternary_search_impl
*
* template<typename _RandomAccessIter,
* typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type,
* typename _Less>
* _RandomAccessIter
* ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find, _Less less);
*
* template<typename _RandomAccessIter,
* typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type>
* _RandomAccessIter
* ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find);
*/
#include <functional>
namespace ternary_search_impl
{
template<typename _RandomAccessIter,
typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type,
typename _Less>
_RandomAccessIter
ternarySearchImpl(_RandomAccessIter first,
_RandomAccessIter last,
const _RandomAccessIter ¬FoundSentinel,
const _ValueType &find,
_Less less)
{
if (first <= last)
{
auto dist = std::distance(first, last);
auto leftMid = first + dist / 3, rightMid = last - dist / 3;
auto lessThanLeftMid = less(find, *leftMid), greaterThanLeftMid = less(*leftMid, find),
lessThanRightMid = less(find, *rightMid), greaterThanRightMid = less(*rightMid,
find);
if (lessThanLeftMid == greaterThanLeftMid)
return leftMid;
if (lessThanRightMid == greaterThanRightMid)
return rightMid;
if (lessThanLeftMid)
return ternarySearchImpl(first, leftMid - 1, notFoundSentinel, find, less);
else if (greaterThanRightMid)
return ternarySearchImpl(rightMid + 1, last, notFoundSentinel, find, less);
else
return ternarySearchImpl(leftMid + 1, rightMid - 1, notFoundSentinel, find, less);
}
return notFoundSentinel;
}
} // ternary_search_impl
template<typename _RandomAccessIter,
typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type,
typename _Less>
_RandomAccessIter
ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find, _Less less)
{
if (begin < end)
{
auto res = ternary_search_impl::ternarySearchImpl(begin, end - 1, end, find, less);
return res == end ? end : res;
}
return end;
}
template<typename _RandomAccessIter,
typename _ValueType = typename std::iterator_traits<_RandomAccessIter>::value_type>
_RandomAccessIter
ternarySearch(_RandomAccessIter begin, _RandomAccessIter end, const _ValueType &find)
{
return ternarySearch(begin, end, find, std::less<_ValueType>());
}
|
code/search/src/ternary_search/ternary_search.go | package main
import (
"fmt"
)
// Part of Cosmos by OpenGenus Foundation
func ternarySearch(data []int, left int, right int, value int) int {
if right >= left {
mid1 := left + (right-left)/3
mid2 := right - (right-left)/3
if data[mid1] == value {
return mid1
}
if data[mid2] == value {
return mid2
}
if value < data[mid1] {
return ternarySearch(data, left, mid1-1, value)
} else if value > data[mid2] {
return ternarySearch(data, mid2+1, right, value)
} else {
return ternarySearch(data, mid1+1, mid2-1, value)
}
}
return -1
}
func main() {
values := []int{1, 2, 3, 4, 5, 12, 30, 35, 46, 84}
fmt.Println(ternarySearch(values, 0, len(values)-1, 5))
fmt.Println(ternarySearch(values, 0, len(values)-1, 7))
}
|
code/search/src/ternary_search/ternary_search.java | public static void main(String[] args) {
//declare a string array with initial size
String[] songs = {"Ace", "Space", "Diamond"};
System.out.println("\nTest binary (String):");
System.out.println(search(songs, "Ace", 0, 3));
}
public static int search(String[] x, String target, int start, int end) {
if (start < end) {
int midpoint1 = start + (end - start) / 3;
int midpoint2 = start + 2 * (end - start) / 3;
if (target.compareTo(x[midpoint1]) == 0) {
return midpoint1;
} else if (target.compareTo(x[midpoint2]) == 0) {
return midpoint2;
} else if (x[midpoint1].compareTo(x[midpoint2]) < 0) {
return search(x, target, midpoint1, end);
} else {
return search(x, target, start, midpoint2);
}
}
return -1;
}
|
code/search/src/ternary_search/ternary_search.js | /*
* Part of Cosmos by OpenGenus Foundation
*/
function ternarySearch(givenList, left, right, absolutePrecision) {
while (true) {
if (Math.abs(right - left) < absolutePrecision) {
return (left + right) / 2;
}
var leftThird = left + (right - left) / 3;
var rightThird = right - (right - left) / 3;
if (givenList[leftThird] < givenList[rightThird]) {
left = leftThird;
} else {
right = rightThird;
}
}
}
|
code/search/src/ternary_search/ternary_search.kt | // Part of Cosmos by OpenGenus Foundation
fun <T : Comparable<T>> ternarySearch(a: Array<T>, target: T, start: Int = 0, end: Int = a.size): Int {
if (start < end) {
val midpoint1 : Int = start + (end - start) / 3
val midpoint2 : Int = start + 2 * (end - start) / 3
return when (target) {
a[midpoint1] -> midpoint1
a[midpoint2] -> midpoint2
a[midpoint1] < a[midpoint2] -> ternarySearch(a, target, midpoint1, end)
else -> ternarySearch(a, target, start, midpoint2)
}
}
return -1
}
fun main(args: Array<String>) {
val sample: Array<Int> = arrayOf(13, 17, 19, 23, 29, 31, 37, 41, 43)
val key = 23
val result = ternarySearch(sample, key)
println(when (result) {
-1 -> "$key is not in $sample"
else -> "Position of $key is $result"
})
} |
code/search/src/ternary_search/ternary_search.php | <?php
/**
* Part of Cosmos by OpenGenus Foundation
*
* @param array $array
* @param int $low
* @param int $high
* @param int $search
*
* @return int
*/
function ternarySearch(array $array, $low, $high, $search)
{
if ($high >= $low) {
list($lowMiddle, $highMiddle) = [$low + ($high - $low) / 3, $low + 2 * ($high - $low) / 3];
if ($search === $array[$lowMiddle]) {
return $lowMiddle;
} else if ($search === $array[$highMiddle]) {
return $highMiddle;
} else if ($search < $array[$highMiddle]) {
return ternarySearch($array, $low, $lowMiddle, $search);
} else if ($search > $array[$lowMiddle] && $search < $array[$highMiddle]) {
return ternarySearch($array, $lowMiddle, $highMiddle, $search);
} else {
return ternarySearch($array, $highMiddle, $high, $search);
}
}
return -1;
}
echo sprintf(
"Position of %d is %d\n",
$search = 33, ternarySearch($array = [7, 11, 13, 33, 66], 0, count($array) - 1, $search)
);
|
code/search/src/ternary_search/ternary_search.py | def ternary_search(arr, to_find):
left = 0
right = len(arr) - 1
while left <= right:
temp2 = left + (right - left) // 3
temp3 = left + 2 * (right - left) // 3
if to_find == arr[left]:
return left
elif to_find == arr[right]:
return right
elif to_find < arr[left] or to_find > arr[right]:
return -1
elif to_find <= arr[temp2]:
right = temp2
elif to_find > arr[temp2] and to_find <= arr[temp3]:
left = temp2 + 1
right = temp3
else:
left = temp3 + 1
return -1
|
code/search/src/ternary_search/ternary_search.rs | // Part of Cosmos by OpenGenus Foundation
fn main() {
let nums = vec![1, 3, 5, 7, 9];
let ele = 5;
println!("Sample input list: {:?}", nums);
println!("Searched for {} and found index {}", ele, ternary_search(&nums, 0, nums.len(), ele));
}
fn ternary_search(nums: &Vec<i64>, left: usize, right: usize, x: i64) -> i64 {
if left <= right {
let intvl = (right - left) / 3;
let leftmid = left + intvl;
let rightmid = leftmid + intvl;
if nums[leftmid] == x {
return leftmid as i64
}
if nums[rightmid] == x {
return rightmid as i64;
}
if x < nums[leftmid] {
return ternary_search(&nums, left, leftmid, x);
}
else if x > nums[leftmid] && x < nums[rightmid] {
return ternary_search(&nums, leftmid, rightmid, x);
}
else {
return ternary_search(&nums, rightmid, right, x);
}
}
-1
}
|
code/search/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/search/test/test_search.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*/
#define CATCH_CONFIG_MAIN
#include "../../../test/c++/catch.hpp"
#include <list>
#include <vector>
#include <iterator>
#include <algorithm>
#include "../src/binary_search/binary_search.cpp"
#include "../src/exponential_search/exponential_search.cpp"
#include "../src/fibonacci_search/fibonacci_search.cpp"
#include "../src/interpolation_search/interpolation_search.cpp"
#include "../src/jump_search/jump_search.cpp"
#include "../src/linear_search/linear_search.cpp"
#include "../src/ternary_search/ternary_search.cpp"
// #define InputIterator
#define RandomAccessIterator
#define SearchFunc binarySearch
#ifdef InputIteratorContainer
#define Container list
#endif
#ifdef RandomAccessIterator
#define Container vector
#endif
using std::list;
using std::vector;
TEST_CASE("search algorithm")
{
// common interface
int *(*psf)(int *, int *, const int &);
Container<int>::iterator (*vsf)(Container<int>::iterator,
Container<int>::iterator,
const int &);
// substitute our search algorithm
vsf = SearchFunc;
psf = SearchFunc;
auto testWithRandomValue = [&](size_t size)
{
using std::rand;
using std::sort;
// size == 0: avoid division by 0
int boundaryOfPossibleValue =
static_cast<int>(size + (size == 0));
// initial containers
int *podPtr = new int[size];
auto podPtrEnd = podPtr + size;
Container<int> container(size);
// initial random values for containers
for (size_t i = 0; i < size; ++i)
{
int randomValue = rand() % boundaryOfPossibleValue;
podPtr[i] = randomValue;
container[i] = randomValue;
}
sort(podPtr, podPtrEnd);
sort(container.begin(), container.end());
// based standard search
// if found then compare to value, else compare to pointer is end
// range of random values is [0:boundOfPossibleValue]
// +/-30 is test out of boundary
for (int i = -30; i < boundaryOfPossibleValue + 30; ++i)
if (std::binary_search(podPtr, podPtrEnd, i))
{
CHECK(*psf(podPtr, podPtrEnd, i) == i);
CHECK(*vsf(container.begin(), container.end(), i) == i);
}
else
{
CHECK(psf(podPtr, podPtrEnd, i) == podPtrEnd);
CHECK(vsf(container.begin(),
container.end(), i) == container.end());
}
delete[] podPtr;
};
SECTION("empty")
{
testWithRandomValue(0);
}
SECTION("1 elem")
{
for (int i = 0; i < 1000; ++i)
testWithRandomValue(1);
}
SECTION("2 elems")
{
for (int i = 0; i < 1000; ++i)
testWithRandomValue(2);
}
SECTION("3 elems")
{
for (int i = 0; i < 1000; ++i)
testWithRandomValue(3);
}
SECTION("random size")
{
for (int i = 0; i < 1000; ++i)
testWithRandomValue(50 + std::rand() % 100);
}
SECTION("large size")
{
testWithRandomValue(1e6 + std::rand() % 10000);
}
}
|
code/search/test/test_search.py | import sys
import os
sys.path.insert(0, os.path.realpath(__file__ + "/../../"))
import bisect
import random
import src.linear_search.linear_search
import src.binary_search.binary_search
import src.fibonacci_search.fibonacci_search
import src.ternary_search.ternary_search
import src.jump_search.jump_search
import src.interpolation_search.interpolation_search
import src.exponential_search.exponential_search
search_func = None
search_funcs = []
search_funcs += [src.linear_search.linear_search.linear_search]
search_funcs += [src.binary_search.binary_search.binary_search_recursive]
search_funcs += [src.binary_search.binary_search.binary_search_interactive]
search_funcs += [src.fibonacci_search.fibonacci_search.fibonacci_search]
search_funcs += [src.ternary_search.ternary_search.ternary_search]
search_funcs += [src.jump_search.jump_search.jump_search]
search_funcs += [src.interpolation_search.interpolation_search.interpolation_search]
search_funcs += [src.exponential_search.exponential_search.exponential_search]
COMPARE_MODE = "ANY_SAME_NODE"
'COMPARE_MODE = "LOWER_BOUND"'
ELEM_MODE = "ALLOW_DUPLICATE"
'ELEM_MODE = "UNIQUE"'
def index(a, x):
"Locate the leftmost value exactly equal to x"
i = bisect.bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
return -1
def fill(arr, size):
i = 0
if ELEM_MODE == "ALLOW_DUPLICATE":
while len(arr) < size:
arr.extend([i])
if random.randint(0, 2) % 2:
arr.extend([i])
i += 1
elif ELEM_MODE == "UNIQUE":
while len(arr) < size:
arr.extend([i])
i += 1
def testSizeByTimes(size, times):
for t in range(times):
arr = []
fill(arr, size)
for i in range(-30, len(arr) * 2):
expect = index(arr, i)
actual = search_func(arr, i)
same = expect == actual
diff = expect in range(0, len(arr)) and arr[expect] == arr[actual]
if COMPARE_MODE == "ANY_SAME_NODE":
assert same or diff
elif COMPARE_MODE == "LOWER_BOUND":
assert same
if __name__ == "__main__":
for func in search_funcs:
search_func = func
print(search_func)
testSizeByTimes(0, 1)
testSizeByTimes(1, 1)
testSizeByTimes(2, 1000)
testSizeByTimes(3, 1000)
testSizeByTimes(random.randint(1e4, 1e5), 1)
print("passed")
|
code/selection_algorithms/src/README.md | # QuickSelect
It is a selection algorithm to find the k-th smallest element in an unordered list. It is related to the quick sort sorting algorithm.
## Complexity
O(n) (with a worst-case of O(n^2))
---
<p align="center">
A massive collaborative effort by <a href="https://github.com/OpenGenus/cosmos">OpenGenus Foundation</a>
</p>
---
|
code/selection_algorithms/src/median_of_medians/median_of_medians.c | // Part of OpenGenus/cosmos
// Author : ABDOUS Kamel
// The median of medians algorithm.
// Deterministic select algorithm that executes
// in O(n) in the worst case.
#include <stdio.h>
#define MEDIAN_GROUPS_SIZE 5
int partition(int array[], int beg, int end, int pivotIndex)
{
int pivotValue = array[pivotIndex];
array[pivotIndex] = array[end];
array[end] = pivotValue;
int i, swapVar, curIndex = beg;
for(i = beg; i < end; ++i)
{
if(array[i] < pivotValue)
{
swapVar = array[curIndex];
array[curIndex] = array[i];
array[i] = swapVar;
curIndex++;
}
}
array[end] = array[curIndex];
array[curIndex] = pivotValue;
return curIndex;
}
void insertionSort(int array[], int beg, int end)
{
int i, j, key;
for(i = beg + 1; i <= end; ++i)
{
key = array[i];
j = i - 1;
while(j >= beg && array[j] > key)
{
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
// Returns the median of medians.
int getMedianOfMedians(int array[], int beg, int end)
{
int arraySize = end - beg + 1;
if(arraySize <= MEDIAN_GROUPS_SIZE)
return beg + (arraySize / 2);
int i = beg,
medGroupsEnd = beg,
medianPos, j, swapVar;
// Store in the beginning of the array the medians of medians (array[beg..medGroupsEnd]).
while(i <= end)
{
j = i + MEDIAN_GROUPS_SIZE - 1;
if(j > end)
j = end;
insertionSort(array, i, j);
medianPos = i + (j - i + 1) / 2;
swapVar = array[medGroupsEnd];
array[medGroupsEnd] = array[medianPos];
array[medianPos] = swapVar;
medGroupsEnd++;
i = j + 1;
}
return getMedianOfMedians(array, beg, medGroupsEnd);
}
// Returns the k-th smallest element in array[beg..end]
int selectKth(int array[], int beg, int end, int k)
{
if(end <= beg)
return beg;
int pivotIndex = partition(array, beg, end, getMedianOfMedians(array, beg, end));
if(pivotIndex == k - 1)
return pivotIndex;
else if(pivotIndex < k - 1)
return selectKth(array, pivotIndex + 1, end, k);
else
return selectKth(array, beg, pivotIndex - 1, k);
}
int main()
{
int a[] = {98, 65, 12, 365, 7, 8, 9, 12, 65};
int i;
for(i = 0; i < 8; ++i)
{
printf("%d\n", a[selectKth(a, 0, 8, i + 1)]);
}
return 0;
}
|
code/selection_algorithms/src/median_of_medians/median_of_medians.hs | import Data.List
median :: (Show a, Ord a) => [a] -> a
median xs = select ((length xs) `div` 2) xs
select :: (Show a, Ord a) => Int -> [a] -> a
select i xs
| n <= 5 = (sort xs) !! i
| lengthLower == i = medianOfMedians
| lengthLower < i = select (i - lengthLower - 1) upperPartition
| otherwise = select i lowerPartition
where
n = length xs
medianOfMedians = median (map median (chunksOf 5 xs))
(lowerPartition, _:upperPartition) = partition (\x -> x < medianOfMedians) xs
lengthLower = length lowerPartition
chunksOf :: Int -> [a] -> [[a]]
chunksOf _ [] = []
chunksOf n xs = (take n xs) : (chunksOf n (drop n xs))
|
code/selection_algorithms/src/median_of_medians/median_of_medians.py | def select(A, i):
if len(A) <= 5:
return sorted(A)[i]
chunks = [A[i : i + 5] for i in range(0, len(A), 5)]
medians = [select(chunk, len(chunk) // 2) for chunk in chunks]
medianOfMedians = select(medians, len(medians) // 2)
lowerPartition, upperPartition = (
[a for a in A if a < medianOfMedians],
[a for a in A if a > medianOfMedians],
)
if i == len(lowerPartition):
return medianOfMedians
elif i > len(lowerPartition):
return select(upperPartition, i - len(lowerPartition) - 1)
else:
return select(lowerPartition, i)
|
code/selection_algorithms/src/quick_select.java | // Part of Cosmos by OpenGenus Foundation
//Find kith largest element is equivalent to find (n - k)th smallest element in array.
//It is worth mentioning that (n - k) is the real index (start from 0) of an element.
public class Solution {
public int findKthLargest(int[] nums, int k) {
int start = 0, end = nums.length - 1, index = nums.length - k;
while (start < end) {
int pivot = partion(nums, start, end);
if (pivot < index) start = pivot + 1;
else if (pivot > index) end = pivot - 1;
else return nums[pivot];
}
return nums[start];
}
private int partion(int[] nums, int start, int end) {
int pivot = start, temp;
while (start <= end) {
while (start <= end && nums[start] <= nums[pivot]) start++;
while (start <= end && nums[end] > nums[pivot]) end--;
if (start > end) break;
temp = nums[start];
nums[start] = nums[end];
nums[end] = temp;
}
temp = nums[end];
nums[end] = nums[pivot];
nums[pivot] = temp;
return end;
}
}
|
code/selection_algorithms/src/quick_select.kt | const val MAX = Int.MAX_VALUE
val rand = java.util.Random()
fun partition(list:IntArray, left: Int, right:Int, pivotIndex: Int): Int {
val pivotValue = list[pivotIndex]
list[pivotIndex] = list[right]
list[right] = pivotValue
var storeIndex = left
for (i in left until right) {
if (list[i] < pivotValue) {
val tmp = list[storeIndex]
list[storeIndex] = list[i]
list[i] = tmp
storeIndex++
}
}
val temp = list[right]
list[right] = list[storeIndex]
list[storeIndex] = temp
return storeIndex
}
tailrec fun quickSelect(list: IntArray, left: Int, right: Int, k: Int): Int {
if (left == right) return list[left]
var pivotIndex = left + Math.floor((rand.nextInt(MAX) % (right - left + 1)).toDouble()).toInt()
pivotIndex = partition(list, left, right, pivotIndex)
if (k == pivotIndex)
return list[k]
else if (k < pivotIndex)
return quickSelect(list, left, pivotIndex - 1, k)
else
return quickSelect(list, pivotIndex + 1, right, k)
}
fun main(args: Array<String>) {
val list = intArrayOf(9, 8, 7, 6, 5, 0, 1, 2, 3, 4)
val right = list.size - 1
for (k in 0..9) {
print(quickSelect(list, 0, right, k))
if (k < 9) print(", ")
}
println()
}
|
code/selection_algorithms/src/quick_select.swift | import Foundation
public func kthLargest(_ a: [Int], _ k: Int) -> Int? {
let len = a.count
if k > 0 && k <= len {
let sorted = a.sorted()
return sorted[len - k]
} else {
return nil
}
}
public func random(min: Int, max: Int) -> Int {
assert(min < max)
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
public func randomizedSelect<T: Comparable>(_ array: [T], order k: Int) -> T {
var a = array
func randomPivot<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int) -> T {
let pivotIndex = random(min: low, max: high)
a.swapAt(pivotIndex, high)
return a[high]
}
func randomizedPartition<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int) -> Int {
let pivot = randomPivot(&a, low, high)
var i = low
for j in low..<high {
if a[j] <= pivot {
a.swapAt(i, j)
i += 1
}
}
a.swapAt(i, high)
return i
}
func randomizedSelect<T: Comparable>(_ a: inout [T], _ low: Int, _ high: Int, _ k: Int) -> T {
if low < high {
let p = randomizedPartition(&a, low, high)
if k == p {
return a[p]
} else if k < p {
return randomizedSelect(&a, low, p - 1, k)
} else {
return randomizedSelect(&a, p + 1, high, k)
}
} else {
return a[low]
}
}
precondition(a.count > 0)
return randomizedSelect(&a, 0, a.count - 1, k)
}
|
code/selection_algorithms/src/quickselect.cpp | // This algorithm is similar to quicksort because it
// chooses an element as a pivot and partitions the
// data into two based on the pivot. However, unlike
// quicksort, quickselect only recurses into one side
// - the side with the element it is searching for.
#include <iostream>
#include <vector>
#include <cmath>
#include <cstdlib>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
// Swaps values in vector with given indices
void vSwap(vector<int> &v, int pos1, int pos2)
{
int temp = v[pos1];
v[pos1] = v[pos2];
v[pos2] = temp;
}
int partition(vector<int> &v, int left, int right, int pivotIndex)
{
int pivotValue = v[pivotIndex];
vSwap(v, pivotIndex, right);
int storeIndex = left;
for (int i = left; i < right; i++)
if (v[i] < pivotValue)
{
vSwap(v, storeIndex, i);
storeIndex++;
}
vSwap(v, right, storeIndex);
return storeIndex;
}
// Returns the k-th smallest element of list in left <= k <= right
int select(vector<int> &v, int left, int right, int k)
{
if (left == right)
return v[k];
// Select a random pivot within left and right
int pivotIndex = left + floor(rand() % (right - left + 1));
pivotIndex = partition(v, left, right, pivotIndex);
if (k == pivotIndex)
return v[k];
else if (k < pivotIndex)
return select(v, left, pivotIndex - 1, k);
else
return select(v, pivotIndex + 1, right, k);
}
int main()
{
vector<int> v = {70, 45, 98, 66, 34, 18, 23, 6, 8, 99, 69, 24, 10, 97, 88, 42, 74, 4, 5, 100};
cout << select(v, 0, v.size() - 1, 0) << endl;
return 0;
}
|
code/selection_algorithms/src/quickselect.go | package main
import (
"math/rand"
)
func quickselect(list []int, item_index int) int {
return selec(list,0, len(list) - 1, item_index)
}
func partition(list []int, left int, right int, pivotIndex int) int {
pivotValue := list[pivotIndex]
// move pivot to end
list[pivotIndex], list[right] = list[right], list[pivotIndex]
storeIndex := left
for i := left; i < right; i++ {
if list[i] < pivotValue {
// move pivot to its final place
list[storeIndex], list[i] = list[i], list[storeIndex]
storeIndex += 1
}
}
list[right], list[storeIndex] = list[storeIndex], list[right]
return storeIndex
}
func selec(list []int, left int, right int, k int) int {
if left == right {
return list[left]
}
pivotIndex := rand.Intn(right)
// the pivot in its final sorted position
pivotIndex = partition(list, left, right, pivotIndex)
if k == pivotIndex {
return list[k]
} else if k < pivotIndex {
return selec (list, left, pivotIndex - 1, k)
} else {
return selec(list, pivotIndex + 1, right, k)
}
}
func main() {} |
code/selection_algorithms/src/quickselect.py | def quickselect(items, item_index):
def select(lst, l, r, index):
# base case
if r == l:
return lst[l]
# choose random pivot
pivot_index = random.randint(l, r)
# move pivot to beginning of list
lst[l], lst[pivot_index] = lst[pivot_index], lst[l]
# partition
i = l
for j in range(l + 1, r + 1):
if lst[j] < lst[l]:
i += 1
lst[i], lst[j] = lst[j], lst[i]
# move pivot to correct location
lst[i], lst[l] = lst[l], lst[i]
# recursively partition one side only
if index == i:
return lst[i]
elif index < i:
return select(lst, l, i - 1, index)
else:
return select(lst, i + 1, r, index)
if items is None or len(items) < 1:
return None
if item_index < 0 or item_index > len(items) - 1:
raise IndexError()
return select(items, 0, len(items) - 1, item_index)
|
code/selection_algorithms/src/quickselect_stl.cpp | #include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++)
cin >> v[i];
int k;
cin >> k;
nth_element(v.begin(), v.begin() + k, v.end());
cout << v[k] << endl;
return 0;
}
|
code/selection_algorithms/test/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter
|
code/shell_script/Looping/README.md | # Looping Structures in Shell Scripting
Loops are used to implement same problem logic multiple times with slight variation.
Looping structures provided in Shell Scripts are while loop and for loop.
In Shell, following looping structures are available:
[1. For Loop](for_loop)
[2. While loop](while_loop)
|
code/shell_script/Looping/for_loop/for_break.sh | #!/bin/bash
i=1; #initialize variable to 1
for (( ; ; )) #infinite loop
do
echo "$i"
i=$(($i+1))
if [ $i -eq 10 ]
then
break;
fi
done
|
code/shell_script/Looping/for_loop/for_continue.sh | #!/bin/bash
for i in 1 2 3 4 5
do
if [ $i -eq 3 ]
then
continue;
fi;
echo "$i";
done
|
code/shell_script/Looping/for_loop/for_ctype.sh | #!/bin/bash
for (( i=0; i<10; i++ ))
do
echo "$i";
done
|
code/shell_script/Looping/for_loop/for_increment.sh | #!/bin/bash
for i in {1..10}
do
echo "This is $i increment"
done
|
code/shell_script/Looping/for_loop/for_infinite.sh | #!/bin/bash
for (( ; ; ))
do
echo "Infinite loop";
done
|
code/shell_script/Looping/for_loop/for_items.sh | for i in Hello World "Hello World" Bye
do
echo "$i"
done
|
code/shell_script/Looping/for_loop/for_jump.sh | #!/bin/bash
for i in {1..10..2}
do
echo "This is $i";
done
|
code/shell_script/Looping/for_loop/for_seq.sh | #!/bin/bash
for i in `seq 1 10`
do
echo "This is $i increment"
done
|
code/shell_script/Looping/for_loop/forloop_tuple.sh | #!/bin/bash
for i in 1 2 3 4 5 6 7 8
do
echo "This is loop $i";
done
|
code/shell_script/Looping/while_loop/while_basics.sh | #!/bin/bash
i=1
while [ $i -le 5 ]
do
echo "$i";
i=$(($i+1));
done
|
code/shell_script/Looping/while_loop/while_infinite.sh | #!/bin/bash
while :
do
echo "infinite loop";
done
|
code/shell_script/README.md | # Shell Scripting
# Table Of Contents
[1. Basic Shell Scripts](basic_scripts)
[2. Control Structures In Shell](control_structures)
[3. Functions](functions)
[4. Looping structures](Looping)
[5. Make and Makefile](make_and_makefile)
Shell Scripting comprises of two terms:
**Shell:** In Linux OS, Shell is the interface between CPU kernel and Linux Actor (Users like humans, machine etc.)
Linux Shell provides interface via a command line with $ prompt for secondary users and # prompt for root or primary users.
**Note:** Shell is an **interpreter**, thus if we specify a set of codes in shell, it will execute all of them one by one even if an intermediate command gives an error/exception.
Linux shell can be of following types:
1. Bourne Shell (sh)
2. Bourne Again Shell (bash)
3. Korn Shell (ksh)
4. Turbo Shell (tcsh)
5. C-Shell (csh) etc.
**Script:** A script in general is a set of code that automatically executes.
Scripts can be invoked in following ways:
1. using **triggers**
2. using schedulers like **Crontab**, **Anacron**, **at** etc.
3. Manual Invocation
Some of the most popular scripting languages are Python, JavaScript and Shell Scripts.
**Shell Scripts:** Shell scripts are set of codes written in Linux shell to perform following tasks:
1. Automate the workflow
2. Perform batch tasks
3. Perform repetitive tasks
4. Schedule the tasks using Schedulers like Cron etc.
|
code/shell_script/basic_scripts/README.md | # Basic Shell Scripts
[1. Hello World Code](src/HelloWorld.sh)
[2. Variable Declaration](src/variable.sh)
[3. Taking input from User](src/readvar.sh)
[4. Standard Input and Output example](src/inout.sh)
[5. Unsetting variables](src/deletevar.sh)
[6. Special Variables](src/specialvar.sh)
[7. Command line arguments in Shell](src/commandlineargument.sh)
[8. Basic Arithmetic Operation](src/arithmetic.sh)
|
code/shell_script/basic_scripts/src/HelloWorld.sh | #!/bin/bash
echo "Hello World"
|
code/shell_script/basic_scripts/src/arithmetic.sh | #!/bin/bash
echo "Arithmetic Operations on Shell";
read -p "Enter an Real value: " val1
read -p "Enter another Real value: " val2
echo "Addition: $(($val1+$val2))"
echo "Subtraction: $(($val1-$val2))"
echo "Multiplication: $(($val1*$val2))"
div=$(($val1/$val2))
echo "Division: ${div}"
|
code/shell_script/basic_scripts/src/commandlineargument.sh | #!/bin/bash
echo "Command Line Arguments"
echo "File name: $0";
echo "First Argument: $1";
echo "Second Argument: $2";
echo "Number of Arguments sent: $#";
echo "All arguments in same quotes: $*";
echo "All arguments in individual quotes: $@";
|
code/shell_script/basic_scripts/src/deletevar.sh | #!/bin/bash
var1="Variable to be deleted!";
echo "$var1";
unset var1;
echo "Printing unset variable: $var1";
# Trying unset keyword on readonly
readonly var2="Readonly var";
echo $var2;
unset var2;
echo $var2;
|
code/shell_script/basic_scripts/src/inout.sh | #!/bin/bash
echo "Hello $(whoami)! I am your assistant!"
read -p "Enter your real name: " name
echo "Hello $name"
|
code/shell_script/basic_scripts/src/readvar.sh | #!/bin/bash
# This is how you add comments
# Reading variable without promptings users
read var1
echo "$var1"
# Reading variable by prompting user
read -p "Enter a value: " var2
echo "$var2"
# Reading a silent variable by prompting user
read -sp "Enter a value: " var3
echo "" # By default it has an endline attached
echo "$var3"
|
code/shell_script/basic_scripts/src/specialvar.sh | #!/bin/bash
echo "Current File Name: $0"
echo "Process number of current Shell: $$"
echo "Process Number of last background command: $!"
echo "Exit ID of last executed command: $?"
|
code/shell_script/basic_scripts/src/variable.sh | #!/bin/bash
# creating a normal variable
var1="Variable 1"; # No spacing between variable name and value else error
echo $var1;
# Changing value of variable 1
var1="Variable 1 updated";
echo $var1;
# Creating readonly variable
readonly var2="Readonly var";
echo $var2;
var2="Can I change?";
echo $var2;
|
code/shell_script/control_structures/README.md | # Control Structures in Shell Scripting
Control structures are structures that are used in decision making.
A condition is checked and different execution paths can be defined based on whether the condition is true or false.
In Shell Scripts, we have two control structures:
1. If Elif Else fi
2. Switch cases
|
code/shell_script/control_structures/src/if_elif_else.sh | #!/bin/bash
echo "Enter two numbers"
read num1
read num2
if [ $num1 -gt $num2 ]
then
echo "$num1 is greater than $num2"
elif [ $num1 -eq $num2 ]
then
echo "Both numbers are equal"
else
echo "$num2 is greater than $num1"
fi
|
code/shell_script/control_structures/src/if_else.sh | #!/bin/bash
read -p "Enter username: " name
if [ $name == "admin" ]
then
echo "Access Granted"
else
echo "Access Denied"
fi
|
code/shell_script/control_structures/src/switch_case.sh | #!/bin/bash
read -p "Enter your name: " name
case $name in
admin) echo "Access Granted! Welcome Admin" ;;
root) echo "Access Granted! Welcome root" ;;
*) echo "Access Denied" ;;
esac
|
code/shell_script/deleting_old_archives.sh | #!bin/bash
cd /home/kshitiz/archives
rm $(find -mtime +2 -name "*.tar")
rm $(find -mtime +2 -name "*.tar.gz")
rm $(find -mtime +2 -name "*.tar.bz2")
|
code/shell_script/functions/README.md | # Functions in Shell Scripting
Functions are subsets of a code that implement an independent programming logic.
For example, to create a four function calculator, independent programming logic are:
1. Addition function
2. Multiplication function
3. Division function
4. Subtraction function
Function allows us to divide a larger problem into smaller independent problem which may lead to better understandability and debugging.
One major advantage of functions are **code reuse.**
A function, once written, need not to be defined again for doing a same task.
A task can be done in repetition easily with a function call using the function name.
|
code/shell_script/functions/src/func_parameters.sh | #!/bin/bash
function1()
{
echo "Parameter 0 (File Name): $0"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
}
function1 p1 p2;
|
code/shell_script/functions/src/function.sh | #!/bin/bash
# Create function
function1()
{
echo "Inside Function body";
}
# Invoke Function using function name
function1
|
code/shell_script/functions/src/multicall.sh | #!/bin/bash
add()
{
return $(($1+$2))
}
multiply()
{
return $(($1*$2))
}
# Call Addition for 3 and 4 == 7
add 3 4
echo "$?"
# Call multiplication for 3 and 4 == 12
multiply 3 4
echo "$?"
# Call Addition for 5 and 4 == 9
add 5 4
echo "$?"
|
code/shell_script/functions/src/multiplefunctioncall.sh | #!/bin/bash
add()
{
return $(($1+$2))
}
multiply()
{
return $(($1*$2))
}
# Call Addition for 3 and 4 == 7
add 3 4
# Call multiplication for 3 and 4 == 12
multiply 3 4
# Call Addition for 5 and 4 == 9
add 5 4
# Store answer (always stores final function call returned value)
ans=$?
echo "$ans"
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.