filename stringlengths 7 140 | content stringlengths 0 76.7M |
|---|---|
code/shell_script/functions/src/nestedfunction.sh | #!/bin/bash
echo "Nested functions"
# First function
function1()
{
echo "Function 1 body"
function2;
}
# Second function
function2()
{
echo "Function 2 body"
}
function1
|
code/shell_script/functions/src/return_code.sh | #!/bin/bash
function1()
{
return $(($1*$2))
}
echo "Multiplication in Shell using Functions"
echo "Enter two numbers"
read num1
read num2
function1 $num1 $num2
mul=$?
echo "Multiplied value is $mul"
|
code/shell_script/functions/src/scope.sh | #!/bin/bash
# Declaring a global variable
gvar="I am the global variable!!!"
# Define a function
function1()
{
# Declaring a local variable
lvar="I am the local variable"
echo "$gvar"
echo "$lvar"
}
# Call the function
function1
|
code/shell_script/make_and_makefile/Makefile | mycalculator: main.c mymath.h add.c subtract.c multiply.c divide.c
gcc -o mycalculator main.c mymath.h add.c subtract.c multiply.c divide.c
|
code/shell_script/make_and_makefile/README.md | <div align="center">
<img src="https://github.com/kshitizsaini113/cosmos/blob/master/code/shell_script/make_and_makefile/make.png">
</div>
### Make
An automation tool predominantly used to compile and construct the binary executable files from a complex source code involving multiple imports and libraries.
### Mak... |
code/shell_script/make_and_makefile/add.c | #include "mymath.h"
int add(int a, int b) {
return a + b;
}
|
code/shell_script/make_and_makefile/divide.c | #include "mymath.h"
int divide(int a, int b) {
return a / b;
}
|
code/shell_script/make_and_makefile/main.c | #include<stdio.h>
#include "mymath.h"
int main() {
int a, b;
printf("Hello World\n\n");
printf("Enter Two Numbers(A B): ");
scanf("%d %d", &a, &b);
printf("Addition: %d\n", add(a, b));
printf("Subtraction: %d\n", subtract(a, b));
printf("Multiplication: %d\n", multiply(a, b));
printf("Division: %d\n\n", divi... |
code/shell_script/make_and_makefile/multiply.c | #include "mymath.h"
int multiply(int a, int b) {
return a * b;
}
|
code/shell_script/make_and_makefile/mymath.h | int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
int divide(int a, int b);
|
code/shell_script/make_and_makefile/subtract.c | #include "mymath.h"
int subtract(int a, int b) {
return a - b;
}
|
code/sorting/src/Frequency_Sort/Frequency_Sort.py | from collections import defaultdict
# Sort by Frequency
def sortByFreq(arr, n):
# arr -> Array to be sorted
# n -> Length of Array
# d is a hashmap(referred as dictionary in python)
d = defaultdict(lambda: 0)
for i in range(n):
d[arr[i]] += 1
# Sorting the array 'arr' ... |
code/sorting/src/README.md | # cosmos
Your personal library of every algorithm and data structure code that you will ever encounter.
A large scale collaboration of [OpenGenus](https://github.com/opengenus)
|
code/sorting/src/Wave_Sort/Wave_Sort.py | def sortWave(arr, n):
arr.sort()
# for i in range(0, n, 2):
# if i > 0 and arr[i-1] > arr[i]:
# arr[i], arr[i-1] = arr[i-1], arr[i]
# if i < n-1 and arr[i+1] > arr[i]:
# arr[i], arr[i+1] = arr[i+1], arr[i]
for i in range(0,n-1,2):
arr[i], arr[i+1] = arr[i+1]... |
code/sorting/src/bead_sort/README.md | # Bead sort
**Bead sort**, also called **gravity sort**, is a natural sorting algorithm.
In this algorithm, the idea is to represent positive integers by a set of beads, like those in an abacus. Beads are attached to vertical rods and appear to be suspended in air just before sliding down (a number is read by counting... |
code/sorting/src/bead_sort/bead_sort.c | #include <stdio.h>
#include <stdlib.h>
// Part of Cosmos by OpenGenus Foundation
void bead_sort(int *a, int len)
{
int i, j, max, sum;
unsigned char *beads;
# define BEAD(i, j) beads[i * max + j]
for (i = 1, max = a[0]; i < len; i++)
if (a[i] > max) max = a[i];
beads = calloc(1, max * len);
/* mark the bea... |
code/sorting/src/bead_sort/bead_sort.cpp | #include <vector>
#include <iostream>
using namespace std;
#define BEAD(i, j) beads[i * max + j]
// Part of Cosmos by OpenGenus Foundation
// function to perform the above algorithm
void beadSort(vector<int>& a)
{
// Find the maximum element
int max = a[0];
for (size_t i = 1; i < a.size(); ++i)
if... |
code/sorting/src/bead_sort/bead_sort.cs | /* Part of Cosmos by OpenGenus Foundation */
using System;
using System.Linq;
namespace CS
{
public class BeadSort
{
public BeadSort()
{
}
static int[] Sort(int[] arr) {
int max = arr.Max();
var grid = new bool[arr.Length, max];
int[] leve... |
code/sorting/src/bead_sort/bead_sort.java | import java.util.Arrays;
// Part of Cosmos by OpenGenus Foundation
public class BeadSort {
private enum BeadSortStatus {
MARKED,
NOT_MARKED,
}
public static void main(String[] args) {
int[] arrayToSort = new int[]{4, 1, 6, 2, 40, 5, 3, 8, 7};
System.out.println(Arrays.toStr... |
code/sorting/src/bead_sort/bead_sort.js | // Part of Cosmos by OpenGenus Foundation
function range(x) {
var res = [];
for (var i = 0; i < x; i++) {
res.push(i);
}
return res;
}
function determinePrev(arr, idx) {
return arr
.filter(function(x) {
return x.length > idx;
})
.map(function() {
return 1;
})
.reduce(funct... |
code/sorting/src/bead_sort/bead_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// bead_sort.m
// Created by DaiPei on 2017/10/12.
//
#import <Foundation/Foundation.h>
@interface BeadSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation BeadSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
NSNumber ... |
code/sorting/src/bead_sort/bead_sort.php | <?php
function columns($arr) {
if (count($arr)==0)
return array();
else if (count($arr)==1)
return array_chunk($arr[0],1);
array_unshift($arr,NULL);
$transpose=call_user_func_array('array_map', $arr);
return array_map('array_filter',$transpose);
}
function beadsort($arr) {
foreach (... |
code/sorting/src/bead_sort/bead_sort.py | # Part of Cosmos by OpenGenus Foundation
def bead_sort(obj):
if all([type(x) == int and x >= 0 for x in obj]):
ref = [range(x) for x in obj] # for reference
else:
raise ValueError("All elements must be positive integers")
inter = [] # for intermediate
ind = 0 # for index
prev = su... |
code/sorting/src/bead_sort/bead_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// bead_sort.swift
// Created by DaiPei on 2017/10/12.
//
import Foundation
func beadSort(_ array: inout [Int]) {
let n = array.count
var m = Int.min
// find the max value
for i in 0..<n {
if array[i] > m {
m = array[i]
}
... |
code/sorting/src/bead_sort/bead_sort_numpy.py | # Part of Cosmos by OpenGenus Foundation
import numpy as np
def bead_sort(arr):
"""
>>> bead_sort([5, 3, 1, 7, 4, 1, 1, 20])
[1, 1, 1, 3, 4, 5, 7, 20]
"""
# expand input array to table of beads
beads = np.zeros((len(arr), max(arr)), int)
for i, x in enumerate(arr):
beads[i, :x] = 1... |
code/sorting/src/bogo_sort/README.md | # Bogosort
Bogosort or **permutation sort** is an extremely inefficient sorting algorithm. This is due to it's random nature: it randomly generates permutations of it's input until it finds one that is sorted. It has no use in practical applications.
## Explanation
Consider an array: `[ 2 3 5 0 1 ]`
```
5 3 2 0 1 (1s... |
code/sorting/src/bogo_sort/bogo_or_permutation_sort.py | # Python program for implementation of Bogo Sort or Permutation Sort
import random
# Sorts array a[0..n-1] using Bogo sort
def bogoSort(a):
n = len(a)
while (is_sorted(a)== False):
shuffle(a)
# To check if array is sorted or not
def is_sorted(a):
n = len(a)
for i in range(0, n-1):
if (a[i] > a[i+1] ):
retu... |
code/sorting/src/bogo_sort/bogo_sort.c | /* Part of cosmos by OpenGenus Foundation */
/*
* bogo_sort.c
* created by Riya
*/
#include <stdio.h>
#include <stdlib.h>
int
main()
{
int num[10]={1, 4, 7, 5, 9, 2, 6, 3, 8, 0};
int i;
bogosort(num, 10);
printf("The array after sorting is:");
... |
code/sorting/src/bogo_sort/bogo_sort.cpp | /* Part of Cosmos by OpenGenus Foundation */
// C++ implementation of BogoSort by ldaw
#include <algorithm>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
bool isSorted(const std::vector<int> &v)
{
int i = v.size();
while (--i > 0)
if (v[i] < v[i - 1])
return fal... |
code/sorting/src/bogo_sort/bogo_sort.fs | //Part of Cosmos by OpenGenus Foundation
open System
let rnd = Random()
//Simple method to shuffle lists, not really random in terms of crypthography
let shuffle (x:IComparable list)=
List.sortBy(fun x -> rnd.Next()) x
let isSorted (sList:IComparable list)=
let folder = fun (a,b) x -> (a && (b<=x),x)
fst ... |
code/sorting/src/bogo_sort/bogo_sort.go | //Part of Cosmos Project by OpenGenus Foundation
//Bogo Sort implementation on golang
//Written by Guilherme Lucas(guilhermeslucas)
package main
import (
"fmt"
"sort"
"math/rand"
)
func shuffle(arr []int) []int {
for i := range arr {
j := rand.Intn(i + 1)
arr[i], arr[j] = arr[j], arr[i]
}
return a... |
code/sorting/src/bogo_sort/bogo_sort.java | public class Bogosort {
public static void main(String[] args) {
if (args.length == 1) {
String[] arr = args[0].split(",");
Integer[] intArr = new Integer[arr.length];
for (int i = 0; i < arr.length; i++) {
intArr[i] = Integer.parseInt(arr[i]);
... |
code/sorting/src/bogo_sort/bogo_sort.js | function bogosort(arr) {
var isSorted = function(arr) {
for (var i = 1; i < arr.length; i++) {
if (arr[i - 1] > arr[i]) {
return false;
}
}
return true;
};
function shuffle(arr) {
var count = arr.length,
temp,
index;
while (count > 0) {
index = Math.floo... |
code/sorting/src/bogo_sort/bogo_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// bogo_sort.m
// Created by DaiPei on 2017/10/14.
//
#import <Foundation/Foundation.h>
@interface BogoSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation BogoSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
while (![... |
code/sorting/src/bogo_sort/bogo_sort.pl | /* Part of Cosmos by OpenGenus Foundation */
/*
* Implementation of bogo_sort in prolog by arvchristos
* using random_permutation predicate
* usage: bogo_sort(List_unsorted, List_sorted).
* true when List_sorted is a sorted permutation of List List_unsorted
*
* Predicate ...
*/
ordered([_]).
ordered([H|[H1|T]]) :-
... |
code/sorting/src/bogo_sort/bogo_sort.py | import random
# Part of Cosmos by OpenGenus Foundation
def bogo_sort(l):
while not in_order(l):
random.shuffle(l)
return l
def in_order(l):
if not l:
return True
last = l[0]
for x in l[1:]:
if x < last:
return False
last = x
return True
if __name... |
code/sorting/src/bogo_sort/bogo_sort.rb | def bogosort(arr)
arr.shuffle! until in_order?(arr)
arr
end
def in_order?(arr)
return true if arr.empty?
last = arr[0]
arr[1...arr.length].each do |x|
return false if x < last
last = x
end
true
end
p bogosort([3, 2, 1])
|
code/sorting/src/bogo_sort/bogo_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// bogo_sort.swift
// Created by DaiPei on 2017/10/14.
//
import Foundation
func bogoSort(_ array: inout [Int]) {
while !isSorted(array) {
shuffle(&array)
}
}
private func shuffle(_ array: inout [Int]) {
for i in 0..<array.count {
let j =... |
code/sorting/src/bubble_sort/BubbleSort.asm | ; Author: SYEED MOHD AMEEN
; Email: [email protected]
;----------------------------------------------------------------;
; BUBBLESORT SORT SUBROUTINE ;
;----------------------------------------------------------------;
;-------------------------------------------------... |
code/sorting/src/bubble_sort/README.md | # Bubble Sort
**Bubble Sort** is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.
In computer graphics it is popular for its capability to detect a very small error (like swap of just two elements) in almost-sorted arrays and fix it with just linear com... |
code/sorting/src/bubble_sort/bubble_sort.c | /* Part of Cosmos by OpenGenus Foundation */
#include <stdio.h>
typedef int bool;
/* Swap two elements */
void
swap(int *p, int *q)
{
int temp = *p;
*p = *q;
*q = temp;
}
/* Sort array using bubble sort */
void
bubbleSort(int arr[], int n, bool order)
{
/* Order 1 corresponds to ascending sort */
if (or... |
code/sorting/src/bubble_sort/bubble_sort.cpp | /*
* Part of Cosmos by OpenGenus Foundation
*
* bubble sort synopsis
*
* template<typename _Bidirectional_Iter, typename _Compare>
* void
* bubbleSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare);
*
* template<typename _Bidirectional_Iter>
* void
* bubbleSort(_Bidirectional_Iter begi... |
code/sorting/src/bubble_sort/bubble_sort.cs | /* Part of Cosmos by OpenGenus Foundation */
using System;
using System.Linq;
namespace BubbleSortCSharp
{
class BubbleSort
{
static void sort(int[] a){
for (int i = a.Length - 1; i > 0; i--)
{
for (int j = 0; j <= i - 1; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[... |
code/sorting/src/bubble_sort/bubble_sort.dart | void main() {
List<int> array = [5, 1, 4, 2, 8];
List<int> sortedarray = bubbleSort(array);
print(sortedarray);
}
bubbleSort(List<int> array) {
int lengthOfArray = array.length;
for (int i = 0; i < lengthOfArray - 1; i++) {
print('Index i at pos: ${i}');
for (int j = 0; j < lengthOfArray - i - 1; j++... |
code/sorting/src/bubble_sort/bubble_sort.elm | module BubbleSort exposing (sort)
import Tuple
sort : List a -> (a -> a -> Order) -> List a
sort list order =
let
( swapped, listResult ) =
swapPass ( False, list ) order
in
if swapped then
sort listResult order
else
listResult
swapPass : ( Bool, List a ) -> (a -... |
code/sorting/src/bubble_sort/bubble_sort.exs | """
Part of Cosmos by OpenGenus Foundation
"""
defmodule Sort do
def bubble_sort(list) when length(list)<=1, do: list
def bubble_sort(list) when is_list(list), do: bubble_sort(list, [])
def bubble_sort([x], sorted), do: [x | sorted]
def bubble_sort(list, sorted) do
{rest, [max]} = Enum.split(bubble_move(l... |
code/sorting/src/bubble_sort/bubble_sort.f | !/* Part of Cosmos by OpenGenus Foundation */
!Fortran implementation of bubble sorting algorithm
program bubblesort
parameter (nkt = 8)
real unsorted(nkt)
real sorted(nkt)
data unsorted/144, 89, 4, 9, 95, 12, 86, 25/
REAL :: temp
INTEGER :: i, j
LOGICAL :: swap
DO j = SIZE(unsorted)-1, 1, -1
swap = .... |
code/sorting/src/bubble_sort/bubble_sort.go | /* Part of Cosmos by OpenGenus Foundation */
package main
import "fmt"
func bubbleSort(arrayzor []int) {
swapped := true
for swapped {
swapped = false
for i := 0; i < len(arrayzor)-1; i++ {
if arrayzor[i+1] < arrayzor[i] {
arrayzor[i], arrayzor[i+1] = arrayzor[i+1], arrayzor[i]
swapped = true
}
... |
code/sorting/src/bubble_sort/bubble_sort.hs | -- Part of Cosmos by OpenGenus Foundation
bubblesort :: (Ord a) => [a] -> [a]
bubblesort [] = []
bubblesort [x] = [x]
bubblesort (x:y:ys) = let (z:zs) = bubblesort (y:ys) in
if x < z then x:z:zs else bubblesort (z:x:zs) |
code/sorting/src/bubble_sort/bubble_sort.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Arrays;
/**
* Implements the bubble sort sorting algorithm
*/
public class BubbleSort {
static void bubbleSort(int[] array) {
int flag = 1;
for (int i = 0; i < array.length - 1; i++) {
flag = 1;
for (int j = 0; j < array.length - 1; j++) {
... |
code/sorting/src/bubble_sort/bubble_sort.jl | ### /* Part of Cosmos by OpenGenus Foundation */
### Julia 0.6 Implementation of bubble sorting algorithm
function bubblesort(arr)
n = length(arr)
for i=1:n, j=1:n-i
if (arr[j] > arr[j+1])
arr[j], arr[j+1] = arr[j+1], arr[j]
end
end
end
v = [144 89 4 9 95 12 86 25]
print("unb... |
code/sorting/src/bubble_sort/bubble_sort.js | /* Part of Cosmos by OpenGenus Foundation */
function bubbleSort(items) {
var length = items.length;
for (var i = length - 1; i >= 0; i--) {
//Number of passes
for (var j = length - i; j > 0; j--) {
//Compare the adjacent positions
if (items[j] < items[j - 1]) {
//Swap the numbers
... |
code/sorting/src/bubble_sort/bubble_sort.kt | // Part of Cosmos by OpenGenus Foundation
fun <T : Comparable<T>> bubbleSort(array: Array<T>) {
var flag : Boolean
for (i in array.indices) {
flag = true
for (j in 0 until (array.size - i - 1)) {
if (array[j] > array[j + 1]) {
array[j] = array[j + 1].also { array[j+1]... |
code/sorting/src/bubble_sort/bubble_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// BubbleSort.m
// Created by DaiPei on 2017/10/9.
//
#import <Foundation/Foundation.h>
@interface BubbleSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation BubbleSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
for (... |
code/sorting/src/bubble_sort/bubble_sort.php | <?php
// Part of Cosmos by OpenGenus Foundation */
$array = [0,1,6,7,6,3,4,2];
function bubble_sort(array $array)
{
do {
$swapped = false;
for( $i = 0, $c = count($array) - 1; $i < $c; $i++) {
if($array[$i] > $array[$i + 1]) {
list($array[$i + 1], $array[$i]) = array($array[$i], $array[$i + 1]);
$swap... |
code/sorting/src/bubble_sort/bubble_sort.py | # Part of Cosmos by OpenGenus Foundation
def bubble_sort(arr):
"""
>>> arr = [5, 1, 3, 9, 2]
>>> bubble_sort(arr)
>>> arr
[1, 2, 3, 5, 9]
"""
for i in range(len(arr)):
# Terminate algorithm if no more swaps are to be carried out
is_sorted = True
for j in range(i + 1, ... |
code/sorting/src/bubble_sort/bubble_sort.rb | # Part of Cosmos by OpenGenus Foundation
def bubble_sort(array)
n = array.length
loop do
swapped = false
(n - 1).times do |i|
if array[i] > array[i + 1]
array[i], array[i + 1] = array[i + 1], array[i]
swapped = true
end
end
break unless swapped
end
array
end
an_ar... |
code/sorting/src/bubble_sort/bubble_sort.rs | // Part of Cosmos by OpenGenus Foundation
fn bubble_sort(mut arr: Vec<i32>) -> Vec<i32> {
for _ in 0..arr.len() {
let mut flag = false;
for j in 0..arr.len() - 1 {
if arr[j] > arr[j + 1] {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] ... |
code/sorting/src/bubble_sort/bubble_sort.sh | #!/bin/bash
# Part of Cosmos by OpenGenus Foundation
declare -a array
ARRAYSZ=10
create_array() {
i=0
while [ $i -lt $ARRAYSZ ]; do
array[${i}]=${RANDOM}
i=$((i+1))
done
}
print_array() {
i=0
while [ $i -lt $ARRAYSZ ]; do
echo ${array[${i}]}
i=$((i+1))
done
}
verify_sort() {
i=1
w... |
code/sorting/src/bubble_sort/bubble_sort.sml | (* Bubblesort
* Time complexity: O( n^2 )
*)
fun bubblesort [] = []
| bubblesort (x::xs) =
let
val (y, ys, s) = foldl ( fn (c, (p, ps, s)) =>
if c < p then (p, c::ps, true) else (c, p::ps, s)
) (x, [], false) xs;
val xs' = foldl op:: [] (y::ys)
in
if s then bubblesort xs... |
code/sorting/src/bubble_sort/bubble_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// bubble_sort.swift
// Created by DaiPei on 2017/10/10.
//
import Foundation
func bubbleSort(_ array: inout [Int]) {
let n: Int = array.count
for i in stride(from: 0, to: n - 1, by: 1) {
var swapped = false
for j in stride(from: 0, to: n - i ... |
code/sorting/src/bubble_sort/bubble_sort.ts | /* Part of Cosmos by OpenGenus Foundation */
export function bubbleSort(items: Array<number>): Array<number> {
let swapped: boolean = false;
do {
swapped = false;
// 1. Run through the list.
items.forEach((item: number, index: number, items: Array<number>) => {
// 2. Compare each adjacent pair of element
... |
code/sorting/src/bubble_sort/bubble_sort_efficient.cpp | #include <vector>
#include <iostream>
using namespace std;
void bubbleSort(vector<int> &v)
{
for (size_t i = 0; i < v.size() - 1; i++)
{
bool isSorted = 1;
for (size_t j = 0; j < v.size() - 1 - i; j++)
if (v[j] > v[j + 1])
{
swap(v[j], v[j + 1]);
... |
code/sorting/src/bubble_sort/bubble_sort_extension.swift | /* Part of Cosmos by OpenGenus Foundation */
import Foundation
private func swap<T>(_ array: inout [T], at indexA: Int, and indexB: Int) {
let tmp = array[indexA]
array[indexA] = array[indexB]
array[indexB] = tmp
}
extension Array {
mutating func bubbleSort(compareWith less: (Element, Element) -> Boo... |
code/sorting/src/bubble_sort/bubble_sort_linked_list.cpp | //bubble sort iterative
#include <iostream>
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
using namespace std;
int len(Node *head)
{
Node *temp = head;
int i = 0;
while (temp != NULL)
{
i++;
temp = temp->next;
}
... |
code/sorting/src/bubble_sort/bubble_sort_recursive.cpp | #include <iostream>
#include <vector>
// using namespace std;
/* This program is the bubble sort implementation
in C++ using recursion*/
void bubbleSort(std::vector<int>& v, int n)
{
// Base Case
if (n == 1)
return;
// sorting in a pass
for (int i = 0; i < n - 1; i++){
//comparing the ... |
code/sorting/src/bucket_sort/README.md | # Bucket Sort
Bucket sort is a sorting algorithm that works by distributing the elements of an array into a number of buckets. Then, we apply a sorting algorithm, **insertion sort** for best optimisation to sort elements in each bucket, and finally, take the elements out of buckets in order and put them back to origina... |
code/sorting/src/bucket_sort/bucket_sort.c | #include<stdio.h>
#define SIZE 10 //number of buckets
// Part of Cosmos by OpenGenus Foundation
void bucketSort(int a[], int n) {
int i, j, k, buckets[SIZE];
for(i = 0; i < SIZE; ++i)
buckets[i] = 0;
for(i = 0; i < n; ++i)
++buckets[a[i]];
for(i = 0, j = 0; j < SIZE;... |
code/sorting/src/bucket_sort/bucket_sort.cpp | // C++ program to sort an array using bucket sort
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
// Part of Cosmos by OpenGenus Foundation
// Function to sort arr[] of size n using bucket sort
void bucketSort(vector<float>& arr)
{
// 1) Create n empty buckets
vector<float> b[ar... |
code/sorting/src/bucket_sort/bucket_sort.cs | using System;
using System.Collections.Generic;
using System.Linq;
// Part of Cosmos by OpenGenus Foundation
namespace OpenGenus
{
class Program
{
static void Main(string[] args)
{
var random = new Random();
// generate randomly sized array (length 1-100) with random values
var inputSize = random.Next(1... |
code/sorting/src/bucket_sort/bucket_sort.go | package main
import (
"fmt"
"os"
"strconv"
)
// Part of Cosmos by OpenGenus Foundation
func insertionSort(array []float64) {
for i := 0; i < len(array); i++ {
temp := array[i]
j := i - 1
for ; j >= 0 && array[j] > temp; j-- {
array[j+1] = array[j]
}
array[j+1] = temp
}
}
func bucketSort(array []fl... |
code/sorting/src/bucket_sort/bucket_sort.hs | -- Part of Cosmos by OpenGenus Foundation
import System.Environment
import Data.List (sort) -- using sort as the internal bucket sorting algorithm
flatten :: [[a]] -> [a]
flatten xs = (\z n -> foldr (\x y -> foldr z y x) n xs) (:) []
bucketSort :: (RealFrac a, Ord a) => [a] -> Integer -> [a]
bucketSort [] _ = []
buck... |
code/sorting/src/bucket_sort/bucket_sort.java |
import java.util.ArrayList;
import java.util.Collections;
public class BucketSort {
public static void main(String[] args) {
// TODO Auto-generated method stub
//float[] arr={1,9,4,7,2,8};
double arr[] = {0.89, 0.565, 0.656, 0.1234, 0.665, 0.3434};
bucketSort(arr,arr.length);
}
public static void ... |
code/sorting/src/bucket_sort/bucket_sort.js | // InsertionSort to be used within bucket sort
// Part of Cosmos by OpenGenus Foundation
function insertionSort(array) {
var length = array.length;
for (var i = 1; i < length; i++) {
var temp = array[i];
for (var j = i - 1; j >= 0 && array[j] > temp; j--) {
array[j + 1] = array[j];
}
array[j ... |
code/sorting/src/bucket_sort/bucket_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// bucket_sort.m
// Created by DaiPei on 2017/10/14.
//
#import <Foundation/Foundation.h>
#define DEFAULT_STEP 5
@interface BucketSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
- (void)sort:(NSMutableArray<NSNumber *> *)array withStep:(NSUInteger... |
code/sorting/src/bucket_sort/bucket_sort.php | <?php
// Part of Cosmos by OpenGenus Foundation
function bucket_sort($my_array) {
$n = sizeof($my_array);
$buckets = array();
// Initialize the buckets.
for ($i = 0; $i < $n; $i++) {
$buckets[$i] = array();
}
// Put each element into matched bucket.
foreach ($my_array as $i) {
array_push($buckets[ceil... |
code/sorting/src/bucket_sort/bucket_sort.py | # Part of Cosmos by OpenGenus Foundation
def bucket_sort(A):
buckets = [[] for x in range(10)]
for i, x in enumerate(A):
buckets[int(x * len(buckets))].append(x)
out = []
for buck in buckets:
out += isort(buck)
return out
def isort(A):
if len(A) <= 1:
re... |
code/sorting/src/bucket_sort/bucket_sort.rb | # Part of Cosmos by OpenGenus Foundation
DEFAULT_BUCKET_SIZE = 5
def bucket_sort(input, bucket_size = DEFAULT_BUCKET_SIZE)
print 'Array is empty' if input.empty?
array = input.split(' ').map(&:to_i)
bucket_count = ((array.max - array.min) / bucket_size).floor + 1
# create buckets
buckets = []
bucket_co... |
code/sorting/src/bucket_sort/bucket_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// bucket_sort.swift
// Created by DaiPei on 2017/10/14.
//
import Foundation
private let defaultStep = 5
func bucketSort(_ array: inout [Int]) {
bucketSort(&array, withStep: defaultStep)
}
func bucketSort(_ array: inout [Int], withStep step: Int) {
// find... |
code/sorting/src/bucket_sort/bucket_sorting.cpp | // Implementation of Bucket/Bin Sort Algorithm in C++
// Best Time Complexity O(n+k)
// Worst Time Complexity O(n^2)
// Space Complexity O(n)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
// Function to sort arr[] of
// size n using bucket sort
void bucketSort(float arr[], int n)
{
... |
code/sorting/src/circle_sort/README.md | # Circle Sort
Circle sort algorithm is an **inplace sorting algorithm** in which we compare the first element to the last element of the given array, the second element to the second last element, and so on and then split the array in two and recurse until we get pairs of sorted elements, which are then put together to... |
code/sorting/src/circle_sort/circle_sort.c | /*Part of Cosmos by OpenGenus Foundation*/
#include <stdio.h>
#include <stdlib.h>
void swap(int *p, int *q)
{
int tmp = *p;
*p = *q;
*q = tmp;
}
void print_vector(int *a, int n)
{
for (int i = 0; i < n; i++)
printf("%d ", a[i]);
printf("\n");
}
int circle_sort(int *a, int n, int lower, ... |
code/sorting/src/circle_sort/circle_sort.cpp | /*Part of Cosmos by OpenGenus Foundation*/
#include <iostream>
using namespace std;
void swap(int *p, int *q)
{
int tmp = *p;
*p = *q;
*q = tmp;
}
void print_vector(int *a, int n)
{
for (int i = 0; i < n; i++)
cout << a[i];
cout << endl;
}
int circle_sort(int *a, int n, int lower, int u... |
code/sorting/src/circle_sort/circle_sort.cs | /* Part of Cosmos by OpenGenus Foundation */
using System;
namespace CircleSort
{
public class CircleSort
{
public static void Main()
{
var sortedArray = Sort(new int[]{2, 14, 4, 6, 8, 1, 5, 3, 7, 11, 0, 13, 20, -1});
Console.WriteLine(String.Join(", ", sortedArray));
... |
code/sorting/src/circle_sort/circle_sort.java | /* Part of Cosmos by OpenGenus Foundation */
import java.util.Arrays;
public class CircleSort
{
public static void main(String[] args)
{
int[] sortedArray = Sort(new int[]{2, 14, 4, 6, 8, 1, 5, 3, 7, 11, 0, 13, 20, -1});
System.out.println(String.join(", ", Arrays.toString(sortedArray)));
... |
code/sorting/src/circle_sort/circle_sort.js | // Reference: https://rosettacode.org/wiki/Sorting_Algorithms/Circle_Sort
const circlesort = (arr, lo, hi, swaps) => {
let high;
let low;
let mid;
let t;
if (lo === hi) {
return swaps;
}
high = hi;
low = lo;
mid = Math.floor((hi - lo) / 2);
while (lo < hi) {
if (arr[lo] > arr[hi]) {
... |
code/sorting/src/circle_sort/circle_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// circle_sort.m
// Created by DaiPei on 2017/10/15.
//
#import <Foundation/Foundation.h>
@interface CircleSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation CircleSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
whi... |
code/sorting/src/circle_sort/circle_sort.py | # Python program to implement circle sort
# Part of Cosmos by OpenGenus Foundation
# function to swap 2 elements of a list
def swap(a, i, j):
temp = a[i]
a[i] = a[j]
a[j] = temp
# recursive function to perfrom circle sort on the given list
def circle_sort(a, lower, upper, swaps):
# base case
if lo... |
code/sorting/src/circle_sort/circle_sort.swift | /* Part of Cosmos by OpenGenus Foundation */
//
// circle_sort.swift
// Created by DaiPei on 2017/10/14.
//
import Foundation
func circleSort(_ array: inout [Int]) {
while circleSort(&array, low: 0, high: array.count - 1) {}
}
private func circleSort(_ array: inout [Int], low: Int, high: Int) -> Bool {
va... |
code/sorting/src/cocktail_sort/cocktail_sort.c | #include <stdio.h>
/* CocktailSort function is the function used to sort the array using cocktail algorithm. */
/* Cocktailsort is similar to the bubble sort but the complexity is less comparatively. */
void cocktailsort(int l[], int n)
{
/* argument passed is the list of the array to be sorted and the length ... |
code/sorting/src/cocktail_sort/cocktail_sort.java | class CocktailSort {
/** A method to sort the array. The array will be sorted inplace.
* @author KanakalathaVemuru (https://github.com/KanakalathaVemuru)
* @param array an array which has to be sorted
*/
public void sort(int[] array) {
int n = array.length;
int left = 0;
in... |
code/sorting/src/cocktail_sort/cocktail_sort.py | # cocktailsort is the function used to sort array
# it is just like bubble sort with less complexity comparatively
def cocktailsort(l):
# first indicates the first index of the array
first = 0
# k is the variable that counts the length of the array
k = len(l)
# last indicates the last index element ... |
code/sorting/src/comb_sort/README.md | # Comb sort
The comb sort is a variant of bubble sort.
In comb sort, gaps (distance of two items from each other) are introduced. The gap in bubble sort is 1. The gap starts out as a large value, and, after each traversal, the gap is lessened, until it becomes 1, where the algorithm basically degrades to a bubble sort.... |
code/sorting/src/comb_sort/comb_sort.c | #include <stdio.h>
int
updateGap(int gap)
{
gap = (gap * 10) / 13;
return (gap < 1 ? 1 : gap);
}
void
combSort(int ar[], int n)
{
int gap = n;
int flag = 0;
while (gap > 1 || flag == 1) {
gap = updateGap(gap);
flag = 0;
for (int i = 0; i < (n - gap); i++) {
... |
code/sorting/src/comb_sort/comb_sort.cpp | #include <iostream>
// Part of Cosmos by OpenGenus Foundation
using namespace std;
int updateGap(int gap)
{
gap = (gap * 10) / 13;
if (gap < 1)
return 1;
else
return gap;
}
void combSort(int ar[], int n)
{
int gap = n;
int flag = 0;
while (gap > 1 || flag == 1)
{
ga... |
code/sorting/src/comb_sort/comb_sort.go | // Part of Cosmos by OpenGenus Foundation
package main
import (
"fmt"
"os"
)
func updateGap(gap int) int {
gap = (gap * 10) / 13
if gap < 1 {
return 1
}
return gap
}
func combSort(ar []int, n int) {
gap := n
flag := false
for gap > 1 || flag {
gap = updateGap(gap)
flag = false
for i := 0; i < (n - ... |
code/sorting/src/comb_sort/comb_sort.java | // Part of Cosmos by OpenGenus Foundation
import java.util.Scanner;
public class CombSort
{
public static void main(String[] args)
{
int i;
Scanner sc = new Scanner(System.in);
System.out.println("Enter no elements you want (Size):");
int size = sc.nextInt();
int[] a = ... |
code/sorting/src/comb_sort/comb_sort.js | // Part of Cosmos by OpenGenus Foundation
function is_array_sorted(arr) {
var sorted = true;
for (var i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
sorted = false;
break;
}
}
return sorted;
}
// Array to sort
// var arr = [1,1,1,1,5,4,4,2,5,666,3,3,34,4,6,2,5];
var iteration... |
code/sorting/src/comb_sort/comb_sort.m | /* Part of Cosmos by OpenGenus Foundation */
//
// comb_sort.m
// Created by DaiPei on 2017/10/15.
//
#import <Foundation/Foundation.h>
@interface CombSort : NSObject
- (void)sort:(NSMutableArray<NSNumber *> *)array;
@end
@implementation CombSort
- (void)sort:(NSMutableArray<NSNumber *> *)array {
NSUIntege... |
code/sorting/src/comb_sort/comb_sort.py | def combsort(array):
gap = len(array)
swap = True
while gap > 1 or swap:
gap = max(1, int(gap / 1.25))
swap = False
for i in range(len(array) - gap):
j = i + gap
if array[i] > array[j]:
array[i], array[j] = array[j], array[i]
sw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.