filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/sorting/src/merge_sort/merge_sort_extension.swift
/* Part of Cosmos by OpenGenus Foundation */ import Foundation extension Array { mutating func mergeSort(compareWith less: (Element, Element) -> Bool) { mergeSort(compareWith: less, low: 0, high: self.count - 1) } private mutating func mergeSort(compareWith less: (Element, Element) -> Bool, low: ...
code/sorting/src/merge_sort/merge_sort_linked_list.c
// Program to mergesort linked list #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } node; node* insert(node *root, int data) { node *tail = malloc(sizeof(node)); tail->data = data; tail->next = NULL; if (!root) { root = tail; ...
code/sorting/src/merge_sort/merge_sort_linked_list.cpp
/* Here ListNode is class containing 'next' for next node, and value for value at node. */ ListNode* mergeSort(ListNode* head) { if (head==NULL||head->next==NULL) { return head; } ListNode* mid = getMid(head); ListNode* leftHalf = mergeSort(head); ListNode* rightHalf ...
code/sorting/src/pancake_sort/pancake_sort.cpp
#include <iostream> #include <vector> #include <algorithm> template <typename T> void pancakeSort(std::vector<T>& container) { for (int size = container.size(); size > 1; --size) { // Find position of max element int maxPos = std::max_element(container.begin(), container.begin() + size) - cont...
code/sorting/src/pigeonhole_sort/README.md
# Pigeonhole Sort The Pigeonhole sort is a sorting technique that is used when the range of keys is relatively small. An array of pigeonholes (buckets, chunks of RAM) is reserved for each possible key value. The records from the unsorted list are scanned and copied into their respective pigeonholes based on their key ...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.c
#include <stdio.h> #include <stdlib.h> // Part of Cosmos by OpenGenus Foundation int main(){ printf("enter the size of array to be sorted:\n"); int n; scanf("%d", &n); int pigeon[n]; printf("now enter the elements of the array:\n"); for(int i=0;i<n;++i){ scanf("%d", &pigeon[i]); } ...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.cpp
#include <vector> #include <iostream> using namespace std; /* Sorts the array using pigeonhole algorithm */ // Part of Cosmos by OpenGenus Foundation void pigeonholeSort(vector<int>& arr) { // Find minimum and maximum values in arr[] int min = arr[0], max = arr[0]; for (size_t i = 1; i < arr.size(); i++) ...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.cs
// Part of Cosmos by OpenGenus Foundation // using System; using System.Collections.Generic; public class Program { //Main entrypoint and test setup public static void Main() { int[] arr = new int[] {12, 11, 6, 2, 16, 7, 9, 18}; PigeonholeSort(ref arr); Console.Write("Sorted order is: "); for...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.go
package main import ( "fmt" ) // Pigeonhole Sort in Golang // Part of Cosmos by OpenGenus Foundation // PigeonholeSort sorts the given slice func PigeonholeSort(a []int) { arrayLength := len(a) // this is used to handle for the edge case where there is nothing to sort if arrayLength == 0 { return } min := ...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.java
/* Part of Cosmos by OpenGenus Foundation */ /* Pigeonhole sorting is a sorting algorithm that is suitable for sorting lists of elements where the number of elements and the number of possible key values are approximately the same. In principle, it resembles Counting Sort. While Counting Sort is a recursive algorit...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.js
/** * Perform a pigeonhole sort on an array of ints. * @param {Array} - array of ints * @returns {Array} - sorted array of ints */ function pigeonholeSort(array) { // Figure out the range. This part isn't really the algorithm, it's // figuring out the parameters for it. const max = Math.max(...array); const...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // pigeonhole_sort.m // Created by DaiPei on 2017/10/19. // #import <Foundation/Foundation.h> @interface PigeonholeSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation PigeonholeSort - (void)sort:(NSMutableArray<NSNumber *> *)arr...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.php
<?php /* Part of Cosmos by OpenGenus Foundation */ /* Example Usage: print_r(pigeonholeSort([9, 2, 17, 5, 16])); */ function pigeonholeSort($array) { $min = min($array); $max = max($array); $numHoles = $max - $min + 1; $holes = array_fill(0, $numHoles, 0); foreach ($array as $item) { $holes[$item - $min] +...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.py
# Part of Cosmos by OpenGenus Foundation def pigeonhole_sort(a): # size of range of values in the list m_min = min(a) m_max = max(a) size = m_max - m_min + 1 # our list of pigeonholes holes = [0] * size # Populating the pigeonholes. for x in a: assert type(x) is int, "integers ...
code/sorting/src/pigeonhole_sort/pigeonhole_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // pigeonhole_sort.swift // Created by DaiPei on 2017/10/18. // import Foundation func pigeonholeSort(_ array: inout [Int]) { // find max and min value in array var max = Int.min var min = Int.max for item in array { if item > max { ...
code/sorting/src/pigeonhole_sort/pigeonholesort.scala
/* Part of Cosmos by OpenGenus Foundation */ import scala.collection.mutable.ArrayBuffer object PigeonHoleSort { def sort(list: List[Int]): List[Int] = { val min = list.min val max = list.max val buffer: ArrayBuffer[Boolean] = ArrayBuffer((min to max).map(_ => false): _ *) list.foreach(x => buffer(x...
code/sorting/src/postmans_sort/postmans_sort.c
// C Program to Implement Postman Sort Algorithm #include <stdio.h> int main() { int arr[100], arr1[100]; int i, j, maxdigits = 0; printf("Enter size of array :"); int count; scanf("%d", & count); printf("Enter elements into array :"); for (i = 0; i < count; ++i) { printf("El...
code/sorting/src/postmans_sort/postmans_sort.cpp
#include <stdio.h> void arrange(int,int); int array[100], array1[100]; int i, j, temp, max, count, maxdigits = 0, c = 0; int main() { int t1, t2, k, t, n = 1; printf("Enter size of array :"); scanf("%d", &count); printf("Enter elements into array :"); // inputing array elements for (i = 0; i < ...
code/sorting/src/quick_sort/README.md
# Quicksort Quicksort is a fast sorting algorithm that takes a **divide-and-conquer approach** for sorting lists. It picks one element as a pivot element and partitions the array around it such that: left side of pivot contains all the elements that are less than the pivot element and right side contains all elements ...
code/sorting/src/quick_sort/dutch_national_flag.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <stdlib.h> #include <iostream> using namespace std; // Dutch National Flag Sort for array items 0,1,2 void flagSort(vector<int> &v) { int lo = 0; int hi = v.size() - 1; int mid = 0; while (mid <= hi) switch (v[mid]) ...
code/sorting/src/quick_sort/quick_sort.c
/*Part of Cosmos by OpenGenus Foundation*/ #include <stdio.h> void swap(int *p, int *q) { int temp = *p; *p = *q; *q = temp; } //Last element is used a spivot //Places elements smaller than pivot to its left side //Places elements larger than pivot to its right side int partition(int a[], int low, int high) { in...
code/sorting/src/quick_sort/quick_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * quick sort synopsis * * namespace quick_sort_impl { * struct quick_sort_tag {}; * struct iterative_quick_sort_tag :quick_sort_tag {}; * struct recursive_quick_sort_tag :quick_sort_tag {}; * * template<typename _Random_Acccess_Iter, typename _Compare> * _Random_...
code/sorting/src/quick_sort/quick_sort.cs
using System; using System.Collections.Generic; /* * Part of Cosmos by OpenGenus Foundation */ namespace ConsoleApplicationQSort { class Program { static void Main(string[] args) { var A = new int[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 }; var sorter = new QSort<int>(A); sorter.Sort(); foreach (var i in sorte...
code/sorting/src/quick_sort/quick_sort.elm
module QuickSort exposing (sort) sort : List a -> (a -> a -> Order) -> List a sort list order = case list of [] -> [] x :: xs -> let less = List.filter (order x >> (==) GT) xs greater = List.filter (o...
code/sorting/src/quick_sort/quick_sort.go
// Quick Sort in Golang // Part of Cosmos by OpenGenus Foundation package main import ( "fmt" "math/rand" ) // QuickSort sorts the given slice func QuickSort(a []int) []int { if len(a) < 2 { return a } left, right := 0, len(a) - 1 pivot := rand.Int() % len(a) a[pivot], a[right] = a[right], a[pivot] for ...
code/sorting/src/quick_sort/quick_sort.hs
-- Part of Cosmos by OpenGenus Foundation quicksort :: (Ord a) => [a] -> [a] quicksort [] = [] quicksort (x:xs) = let less = filter (<x) xs in let greater = filter (>=x) xs in (quicksort less) ++ [x] ++ (quicksort greater)
code/sorting/src/quick_sort/quick_sort.java
// Part of Cosmos by OpenGenus Foundation class QuickSort { int partition(int arr[], int low, int high) { int pivot = arr[high]; // last element is the pivot int i = (low - 1); for (int j = low; j < high; j++) { if (arr[j] <= pivot) { // if j'th element is less than or equal to the pivot i++; // then ...
code/sorting/src/quick_sort/quick_sort.js
/*Part of Cosmos by OpenGenus Foundation*/ //here a is the array name /*low is the initial index for sorting i.e. 0 for sorting whole array*/ /*high is the ending index for sorting i.e. array's length for sorting whole array*/ /*expected call for the function is as follows: quickSort(array, 0, array.length -1);*/ ...
code/sorting/src/quick_sort/quick_sort.lua
function quicksort(t, start, endi) start, endi = start or 1, endi or #t --partition w.r.t. first element if(endi - start < 1) then return t end local pivot = start for i = start + 1, endi do if t[i] <= t[pivot] then if i == pivot + 1 then t[pivot], t[pivot + 1] = t[pivot + 1], t[pivot] else t[pivot...
code/sorting/src/quick_sort/quick_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // quick_sort.m // Created by DaiPei on 2017/10/10. // #import <Foundation/Foundation.h> @interface QuickSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation QuickSort - (void)sort:(NSMutableArray<NSNumber *> *)array { [self so...
code/sorting/src/quick_sort/quick_sort.ml
(* Part of Cosmos by OpenGenus Foundation *) let rec quick_sort = function | [] -> [] | hd :: tl -> let lower, higher = List.partition (fun x -> x < hd) tl in quick_sort lower @ (hd :: quick_sort higher);;
code/sorting/src/quick_sort/quick_sort.py
""" Part of Cosmos by OpenGenus Foundation """ def quick_sort(arr): quick_sort_helper(arr, 0, len(arr) - 1) def quick_sort_helper(arr, first, last): if first < last: splitpoint = partition(arr, first, last) quick_sort_helper(arr, first, splitpoint - 1) quick_sort_helper(arr, splitpo...
code/sorting/src/quick_sort/quick_sort.rb
# Part of Cosmos by OpenGenus Foundation def quick_sort(array, beg_index, end_index) if beg_index < end_index pivot_index = partition(array, beg_index, end_index) quick_sort(array, beg_index, pivot_index - 1) quick_sort(array, pivot_index + 1, end_index) end array end # returns an index of where the ...
code/sorting/src/quick_sort/quick_sort.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Part of Cosmos by OpenGenus Foundation */ // This algorithm taken from https://github.com/servo/rust-quicksort...
code/sorting/src/quick_sort/quick_sort.scala
/* Part of Cosmos by OpenGenus Foundation */ object QuickSort extends App { def quickSort[A <% Ordered[A]](input: List[A]): List[A] = { input match { case Nil => Nil case head :: tail => val (l, g) = tail partition (_ < head) quickSort(l) ::: head :: quickSort(g) } } val inpu...
code/sorting/src/quick_sort/quick_sort.sh
#!/bin/bash # Lomuto partition scheme. # 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 } ve...
code/sorting/src/quick_sort/quick_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // quick_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func quickSort(_ array: inout [Int]) { quickSort(&array, low: 0, high: array.count - 1) } private func quickSort(_ array: inout [Int], low: Int, high: Int) { if low < high { ...
code/sorting/src/quick_sort/quick_sort.ts
// Part of Cosmos by OpenGenus Foundation function quicksort(A: number[]): number[] { let stack = [{ lo: 0, hi: A.length - 1 }]; while (stack.length > 0) { let { lo, hi } = stack.pop(); if (lo >= hi) { continue; } let pivot = A[lo]; let i = lo; let j = hi; let p: number; ...
code/sorting/src/quick_sort/quick_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 quickSort(compareWith less: (Element, Element) -> Bool...
code/sorting/src/quick_sort/quick_sort_in_place.scala
import annotation.tailrec import collection.mutable.{IndexedSeq, IndexedSeqLike} object QuicksortInPlace { def sort[T](data: IndexedSeqLike[T, _])(implicit ord: Ordering[T]): Unit = { sort(data, 0, data.length) } // start inclusive, end exclusive def sort[T](data: IndexedSeqLike[T, _], start: ...
code/sorting/src/quick_sort/quick_sort_median_of_medians.c
#include<stdio.h> #define SIZE 10000 int a[SIZE], b[SIZE]; int count = 0; void swap(int *a,int *b) { *a = *a + *b; *b = *a - *b; *a = *a - *b; } int median(int x, int y, int z) { if((x > y && x < z) || (x > z && x < y)) return 1; else if((y > x && y < z) || (y < x && y > z)) return 2; else return 3; } void qs...
code/sorting/src/quick_sort/quick_sort_three_way.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <stdlib.h> #include <iostream> using namespace std; /* UTILITY FUNCTIONS */ void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void printarr(vector<int> &v) { for (size_t i = 0; i < v.size(); ++i) cout << v[i] ...
code/sorting/src/radix_sort/README.md
# Radix Sort Radix sort is a **non-comparative integer sorting algorithm**. It works by doing digit by digit sort starting from least significant digit to most significant digit. Radix sort uses counting sort as a subroutine to sort the digits in each place value. This means that for a three-digit number in base 10, c...
code/sorting/src/radix_sort/radix_sort.c
#include <stdio.h> #include <stdlib.h> // Part of Cosmos by OpenGenus Foundation // Initial code by GelaniNijraj // Debug by adeen-s int find_max(int* number, int length){ int i, max = number[0]; for(i = 0; i < length; i++) max = number[i] > max ? number[i] : max; return max; } int* sort(int* number, int length){...
code/sorting/src/radix_sort/radix_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <vector> #include <cmath> void radix_sort(std::vector<int> &data) { using namespace std; vector<int> tmp[10]; //store 0~9; int max_data = *(max(std::begin(data), std::end(data))); int n = 1; while (n <= max_data) { ...
code/sorting/src/radix_sort/radix_sort.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1 func radix_sort(data []int) { maxNumber := MinInt for _, v := range data { if v > maxNumber { maxNumber = v } } n := 1 bucket := make([][]int, 10) ...
code/sorting/src/radix_sort/radix_sort.hs
module Radix where import Data.List import Data.Bits -- Part of Cosmos by OpenGenus Foundation -- intoBuckets separates the input list into two lists, one where a bit -- is set, and one where the bit is not set. intoBuckets' odds evens bit [] = (reverse odds, reverse evens) intoBuckets' odds evens bit (x:xs) | x `t...
code/sorting/src/radix_sort/radix_sort.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.ArrayList; import java.util.List; public class RadixSort { public static void main(String[] args) { int[] nums = {100, 5, 100, 19, 320000, 0, 67, 542, 10, 222}; radixSort(nums); printArray(nums); } /** * This method sorts a passed ...
code/sorting/src/radix_sort/radix_sort.js
// Part of Cosmos by OpenGenus Foundation // Implementation of radix sort in JavaScript var testArray = [331, 454, 230, 34, 343, 45, 59, 453, 345, 231, 9]; function radixBucketSort(arr) { var idx1, idx2, idx3, len1, len2, radix, radixKey; var radices = {}, buckets = {}, num, curr; var currLen, radixS...
code/sorting/src/radix_sort/radix_sort.py
# Part of Cosmos by OpenGenus Foundation def radix_sort(number, maxNumber): length = len(number) k = 0 n = 1 temp = [] for i in range(length): temp.append([0] * length) order = [0] * length while n <= maxNumber: for i in range(length): lsd = (number[i] // n) % 10 ...
code/sorting/src/radix_sort/radix_sort.rs
/* Part of Cosmos by OpenGenus Foundation */ fn main() { let mut arr: Vec<u32> = vec![34, 3212, 51, 52, 612, 456, 12, 31, 412, 123, 1, 3]; println!("Unsorted: {:?}", arr); radix_sort(&mut arr); println!("Sorted: {:?}", arr); } fn radix_sort(input: &mut [u32]) { if input.len() == 0 { r...
code/sorting/src/radix_sort/radix_sort.sh
#!/bin/bash read -p "Enter the array size you want: " size i=0 declare -a arrayname while [ $i -lt $size ] do read -p "Enter the $(($i+1)) element of array: " arrayname[i] i=$[$i+1] done echo "Input array is: ${arrayname[@]}" max=0 for el in ${arrayname[@]} do if [ $el -gt $max ] then max=$el fi done ec...
code/sorting/src/selection_sort/README.md
# Selection Sort Selection sort is a simple sorting algorithm. It is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list. The smallest ele...
code/sorting/src/selection_sort/SELCTION_SORT.ASM
; Author: SYEED MOHD AMEEN ; Email: [email protected] ;---------------------------------------------------------------; ; SELECTION SORT SUBROUTINE ; ;---------------------------------------------------------------; ;------------------------------------------------...
code/sorting/src/selection_sort/selection_sort.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> typedef int bool; /* Function to swap 2 array elements */ void swap(int *p, int *q) { int temp = *p; *p = *q; *q = temp; } /* Function to sort an array using Selection sort */ void selectionSort(int arr[], int n, bool order) { int idx...
code/sorting/src/selection_sort/selection_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * selection sort synopsis * * template<typename _Input_Iter, typename _Compare> * void * selectionSort(_Input_Iter begin, _Input_Iter end, _Compare compare); * * template<typename _Input_Iter> * void * selectionSort(_Input_Iter begin, _Input_Iter end); */ #incl...
code/sorting/src/selection_sort/selection_sort.cs
// Part of Cosmos by OpenGenus Foundation public class SelectionSort { public static void Main(string[] args) { int[] items = new int[] {52, 62, 143, 73, 22, 26, 27, 14, 62, 84, 15 }; Sort(items); System.Console.WriteLine("Sorted: "); for (int i = 0; i < items.L...
code/sorting/src/selection_sort/selection_sort.go
package main // Selection Sort in Golang // Part of Cosmos by OpenGenus Foundation import "fmt" func selectionSort(array [8]int) [8]int { for i := 0; i < len(array); i++ { min := i for j := i + 1; j < len(array); j++ { if array[j] < array[min] { min = j } } array[i], array[min] = array[min], array[...
code/sorting/src/selection_sort/selection_sort.hs
-- Part of Cosmos by OpenGenus Foundation selectionsort :: (Ord a) => [a] -> [a] selectionsort [] = [] selectionsort l = let Just (m, i) = minIndex l in m:selectionsort (take i l ++ drop (i+1) l) minIndex :: (Ord a) => [a] -> Maybe (a, Int) minIndex [] = Nothing minIndex (x:xs) = case minIndex xs of Nothing -...
code/sorting/src/selection_sort/selection_sort.java
/** * Utility class for sorting an array using Selection Sort algorithm. Selection * Sort is a basic algorithm for sorting with O(n^2) time complexity. Basic idea * of this algorithm is to find a local minimum, which is the minimum value from * (i+1) to length of the array [i+1, arr.length), and swap it with the cu...
code/sorting/src/selection_sort/selection_sort.js
// Part of Cosmos by OpenGenus Foundation function selectionSort(inputArray) { var len = inputArray.length; for (var i = 0; i < len; i++) { var minAt = i; for (var j = i + 1; j < len; j++) { if (inputArray[j] < inputArray[minAt]) minAt = j; } if (minAt != i) { var temp = inputArray[i]; ...
code/sorting/src/selection_sort/selection_sort.kt
// Part of Cosmos by OpenGenus Foundation import java.util.* fun <T : Comparable<T>> sort(array: Array<T>) { for (i in array.indices) { var min = i for (j in i + 1 until array.size) { /* find local min */ if (array[j] < array[min]) { min = j } ...
code/sorting/src/selection_sort/selection_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // selection_sort.m // Created by DaiPei on 2017/10/9. // #import <Foundation/Foundation.h> @interface SelectionSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation SelectionSort - (void)sort:(NSMutableArray<NSNumber *> *)array {...
code/sorting/src/selection_sort/selection_sort.php
<?php // Part of Cosmos by OpenGenus Foundation function selection_sort($arr) { $n = count($arr); foreach ($arr as $k => $el) { $min = $k; for ($j = $k + 1; $j < $n; $j++) { if ($arr[$j] < $arr[$min]) { $min = $j; } } $hold = $el; ...
code/sorting/src/selection_sort/selection_sort.py
# Part of Cosmos by OpenGenus Foundation def selection_sort(array): for i in range(len(array) - 1): minimumValue = i for j in range(i + 1, len(array)): if array[j] < array[minimumValue]: minimumValue = j temp = array[minimumValue] array[minimumValue] = a...
code/sorting/src/selection_sort/selection_sort.rb
# Part of Cosmos by OpenGenus Foundation def SelectionSort(arr) n = arr.length - 1 i = 0 while i <= n - 1 smallest = i j = i + 1 while j <= n smallest = j if arr[j] < arr[smallest] j += 1 end arr[i], arr[smallest] = arr[smallest], arr[i] if i != smallest i += 1 end end arr =...
code/sorting/src/selection_sort/selection_sort.rs
// Part of Cosmos by OpenGenus Foundation fn selection_sort(mut arr :Vec<i32>) -> Vec<i32> { let len = arr.len(); for i in 0..len-1 { let mut min = i; for j in i+1..len { if arr[j] < arr[min] { min = j; } } if min != i{ ar...
code/sorting/src/selection_sort/selection_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/selection_sort/selection_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // selection_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func selectionSort(_ array: inout [Int]) { for i in stride(from: 0, to: array.count - 1, by: 1) { var min = i for j in i+1..<array.count { if array[j] < a...
code/sorting/src/selection_sort/selection_sort.vb
Module selection_sort ' Part of Cosmos by OpenGenus Foundation Sub Main() ' Example array Dim arr() As Integer = {1, 5, 2, 5, 2, 9, 7} selection_sort.Sort(arr) ' Print the array For i = 0 To arr.Length - 1 Console.Write(arr(i)) If i < arr.Lengt...
code/sorting/src/selection_sort/selection_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 selectionSort(compareWith less: (Element, Element) -> ...
code/sorting/src/shaker_sort/README.md
# Shaker Sort Shakersort or cocktail sort is a _**bidirectional**_ variation of bubble sort. In shaker sort, n elements are sorted in `n/2` phases. Each phase of shaker sort consists of a left to right bubbling pass followed by a right to left bubbling pass. In a bubbling pass pairs of adjacent elements are compared...
code/sorting/src/shaker_sort/shaker_sort.c
/* Part of Cosmos by OpenGenus Foundation */ /*Added by arpank10 */ #include <stdio.h> #include <stdbool.h> /* Cocktail Shaker Sort implementation in C */ void shaker_sort(int a[],int n) { int i=0,j; bool swapped=false; for(i=0;i<n/2;i++) { /* * Indices of the inner loops result from an ...
code/sorting/src/shaker_sort/shaker_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ /* * This is coctail shaker sort (bidirectional buble sort) */ #include <iostream> #include <vector> #include <algorithm> using namespace std; void shaker_sort(vector<int> &v) { bool swap = false; for (unsigned i = 0; i < v.size() / 2; ++i) { for (un...
code/sorting/src/shaker_sort/shaker_sort.cs
using System; using System.Linq; /* Part of Cosmos by OpenGenus Foundation */ namespace OpenGenus { class Program { static void Main(string[] args) { var random = new Random(); var unsorted = Enumerable.Range(1, 20).Select(x => random.Next(1,40)).ToArray(); Console.WriteLine("Unsorted"); Console.Wri...
code/sorting/src/shaker_sort/shaker_sort.go
// Part of Cosmos by OpenGenus Foundation package main import "fmt" func shakerSort(sortMe []int) { beginningIdx := 0 endIdx := len(sortMe) - 1 for beginningIdx <= endIdx { newBeginningIdx := endIdx newEndIdx := beginningIdx swap := false for i := beginningIdx; i < endIdx; i++ { if sortMe[i] > sortMe[i+...
code/sorting/src/shaker_sort/shaker_sort.java
/* Part of Cosmos by OpenGenus Foundation */ public class ShakerSort { static void sort(int[] arr) { boolean swapped; int llim = 0; int rlim = arr.length - 1; int curr = llim; int tmp; while (llim <= rlim) { swapped = false; while (curr + 1 <= rlim) { if (arr[curr] > arr[curr + 1]) { tmp ...
code/sorting/src/shaker_sort/shaker_sort.js
// Part of Cosmos by OpenGenus Foundation // Sort a list using shaker sort (bidirectional bubble sort) function shaker_sort(list) { let swapped = false; let length = list.length; do { // Testing from head to tail of list for (let i = 0; i < length - 1; i++) { if (list[i] > list[i + 1]) { l...
code/sorting/src/shaker_sort/shaker_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // shaker_sort.m // Created by DaiPei on 2017/10/9. // #import <Foundation/Foundation.h> @interface ShakerSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation ShakerSort - (void)sort:(NSMutableArray<NSNumber *> *)array { BOOL...
code/sorting/src/shaker_sort/shaker_sort.php
<?php /* Part of Cosmos by OpenGenus Foundation */ namespace OpenGenus; trait ShakerSortTrait { /** * @param array $list * @return array */ public function sort(array $list) : array { do { $swapped = false; $length = count($list); for ($i = 0; $...
code/sorting/src/shaker_sort/shaker_sort.py
# Part of Cosmos by OpenGenus Foundation import random def shaker_sort(sort_list): beginning_idx = 0 end_idx = len(sort_list) - 1 while beginning_idx <= end_idx: swap = False for i in range(beginning_idx, end_idx): if sort_list[i] > sort_list[i + 1]: sort_list[i...
code/sorting/src/shaker_sort/shaker_sort.rs
/* Part of Cosmos by OpenGenus Foundation */ /* Added by Ondama */ /** Read a line of input **/ fn read () -> String { let mut input = String::new(); std::io::stdin().read_line(&mut input).expect("failed to read from stdin"); input.trim().to_owned() } /** Display a message and parse input **/ fn prompt<T:...
code/sorting/src/shaker_sort/shaker_sort.swift
// Part of Cosmos by OpenGenus Foundation import Foundation; func shaker_sort(v: inout [UInt32]) { let size = v.count; var swap = false; for i in 0 ... size / 2 - 1 { for j in stride(from: i, to: size - i - 1, by: 1) { if v[j] > v[j + 1] { let tmp = v[j]; ...
code/sorting/src/shell_sort/README.md
# Shellsort The Shellsort algorithm is a search algorithm. It's a generalization of the insertion sort that allows the exchange of items that are far apart. The method starts by sorting pair of elements far apart from each other in the array, then progressively reducing the gap between the elements to be compared. ##...
code/sorting/src/shell_sort/shell_sort.c
#include <stdio.h> // Part of Cosmos by OpenGenus Foundation void shell_sort(int *a, int n) { int i, j, gap, temp; /* Assess the array in gaps starting at half the array size - Each gap is a sublist of 2 values */ for(gap = n/2 ; gap > 0 ; gap /= 2) { /* Index at the right value of each gap */ for(i = ...
code/sorting/src/shell_sort/shell_sort.cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; // Part of Cosmos by OpenGenus Foundation void shellSort(vector<int> &ar) { size_t j; for (size_t gap = ar.size() / 2; gap > 0; gap /= 2) for (size_t i = gap; i < ar.size(); i++) { int temp = ar[i]; ...
code/sorting/src/shell_sort/shell_sort.go
package main import ( "fmt" ) func main() { var n int fmt.Println("Please enter the lenght of the array:") fmt.Scan(&n) X := make([]int, n) fmt.Println("Now, enter the elements X0 X1 ... Xn-1") for i := 0; i < n; i++ { fmt.Scanln(&X[i]) } fmt.Printf("Unsorted array: %v\...
code/sorting/src/shell_sort/shell_sort.java
// Java implementation of ShellSort // Part of Cosmos by OpenGenus Foundation class ShellSort { /* An utility function to print array of size n*/ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.pri...
code/sorting/src/shell_sort/shell_sort.js
// Part of Cosmos by OpenGenus Foundation function shellSort(a) { for (var h = a.length; h > 0; h = parseInt(h / 2)) { for (var i = h; i < a.length; i++) { var k = a[i]; for (var j = i; j >= h && k < a[j - h]; j -= h) a[j] = a[j - h]; a[j] = k; } } return a; }
code/sorting/src/shell_sort/shell_sort.kt
import java.util.* fun MutableList<Int>.swap(index1: Int, index2: Int) { val tmp = this[index1] this[index1] = this[index2] this[index2] = tmp } fun MutableList<Int>.shellSort(): MutableList<Int> { var sublistCount = count() / 2 while (sublistCount > 0) { var index = 0 outer@while (index >= 0 && ind...
code/sorting/src/shell_sort/shell_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // shell_sort.m // Created by DaiPei on 2017/10/9. // #import <Foundation/Foundation.h> @interface ShellSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation ShellSort - (void)sort:(NSMutableArray<NSNumber *> *)array { for (in...
code/sorting/src/shell_sort/shell_sort.py
# Part of Cosmos by OpenGenus Foundation def shell_sort(alist): sub_list_count = len(alist) // 2 while sub_list_count > 0: for start in range(sub_list_count): gap_insertion_sort(alist, start, sub_list_count) sub_list_count = sub_list_count // 2 def gap_insertion_sort(alist, start, ...
code/sorting/src/shell_sort/shell_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // shell_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func shellSort(_ array: inout [Int]) { var h = array.count / 2 while h > 0 { for i in h..<array.count { let key = array[i] var j = i while...
code/sorting/src/shell_sort/shellsort.go
package main import "fmt" import "math/rand" func main() { arr := RandomArray(10) fmt.Println("Initial array is:", arr) fmt.Println("") for d := int(len(arr)/2); d > 0; d /= 2 { for i := d; i < len(arr); i++ { for j := i; j >= d && arr[j-d] > arr[j]; j -= d { arr[j], arr[j-d] = arr[j-d...
code/sorting/src/sleep_sort/README.md
# Sleep Sort The **sleep sort** algorithm is closely related to the operating system. Each input is placed in a new thread which will sleep for a certain amount of time that is proportional to the value of its element. For example, a thread with a value of 10 will sleep longer than a thread with a value of 2. The thre...
code/sorting/src/sleep_sort/sleep_sort.c
/* Part of Cosmos by OpenGenus Foundation */ /* sleep sort works both in windows and linux*/ /* WINDOWS SPECIFIC CODE*/ #if defined(WIN32) || defined(_WIN32) || \ defined(__WIN32) && !defined(__CYGWIN__) #include <process.h> #include <windows.h> void routine(void *a) { int n = *(int *)a; Sleep(n); printf("%d ...
code/sorting/src/sleep_sort/sleep_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <iostream> #include <chrono> #include <vector> #include <thread> using namespace std; int main(int argc, char** argv) { vector<thread> threads; for (auto i = 1; i < argc; ++i) { threads.emplace_back( [i, &argv]() { ...
code/sorting/src/sleep_sort/sleep_sort.cs
/* Part of Cosmos by OpenGenus Foundation */ using System; using System.Threading; using System.Linq; namespace dotnetcore { class Program { static void Main(string[] args) { SleepSort(new int[] {5, 4, 1, 2, 3}); } static void SleepSort(int[] data) { data.AsParallel().WithDegreeOfP...
code/sorting/src/sleep_sort/sleep_sort.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" import "runtime" import "time" func sleepNumber(number int, results chan<- int) { time.Sleep(time.Duration(number) * time.Second) results <- number } func sleepSort(data []int) { results := make(chan int, len(data)) for _, v := range data { ...
code/sorting/src/sleep_sort/sleep_sort.java
/* Part of Cosmos by OpenGenus Foundation */ import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num : nums) { new Thread(new Runnable() { public void run() {...