filename
stringlengths
7
140
content
stringlengths
0
76.7M
code/sorting/src/comb_sort/comb_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // comb_sort.swift // Created by DaiPei on 2017/10/15. // import Foundation func combSort(_ array: inout [Int]) { let shrinkFactor = 0.8 var gap = array.count var swapped = true while gap >= 1 || swapped { swapped = false if gap >= 1 {...
code/sorting/src/counting_sort/Counting_sort.php
<?php // function for counting sort function countingsort(&$Array, $n) { $max = 0; //find largest element in the Array for ($i=0; $i<$n; $i++) { if($max < $Array[$i]) { $max = $Array[$i]; } } //Create a freq array to store number of occurrences of //each unique elements in the given ar...
code/sorting/src/counting_sort/README.md
# Counting Sort Counting sort is a a very time-efficient (and somewhat space-inefficient) algorithm based on keys between a specific range. It works by counting the number of objects having distinct key values (kind of hashing)and then doing some arithmetic to calculate the position of each object in the output sequenc...
code/sorting/src/counting_sort/counting_sort.c
#include <stdio.h> #include <string.h> #define RANGE 255 // Part of Cosmos by OpenGenus Foundation // The main function that sort the given string arr[] in // alphabatical order void countSort(char arr[]) { // The output character array that will have sorted arr char output[strlen(arr)]; // Create a cou...
code/sorting/src/counting_sort/counting_sort.cpp
#include <iostream> #include <vector> #include <climits> /* * Part of Cosmos by OpenGenus Foundation */ using namespace std; void countingSort(vector<int> arr, vector<int>& sortedA) { int m = INT_MIN; for (size_t i = 0; i < arr.size(); i++) if (arr[i] > m) m = arr[i]; int freq[m + 1...
code/sorting/src/counting_sort/counting_sort.cs
using System; using System.Collections.Generic; namespace CS { /* Part of Cosmos by OpenGenus Foundation */ class CountingSort { static int[] Sort(int[] arr) { // Count the frequency of each number in the array // The keys in this dictionary are the items themselves,...
code/sorting/src/counting_sort/counting_sort.go
package main // Part of Cosmos by OpenGenus Foundation import "fmt" const MaxUint = ^uint(0) const MaxInt = int(MaxUint >> 1) const MinInt = -MaxInt - 1 var list = []int{-5, 12, 3, 4, 1, 2, 3, 5, 42, 34, 61, 2, 3, 5} func countingSort(list []int) { maxNumber := MinInt minNumber := MaxInt for _, v := range list { ...
code/sorting/src/counting_sort/counting_sort.java
// Java implementation of Counting Sort // Part of Cosmos by OpenGenus Foundation class CountingSort { private void sort(char arr[]) { int n = arr.length; // The output character array that will have sorted arr char output[] = new char[n]; // Create a count array to store count of ...
code/sorting/src/counting_sort/counting_sort.js
// Part of Cosmos by OpenGenus Foundation function countingSort(arr, min, max) { var i, z = 0, count = []; for (i = min; i <= max; i++) { count[i] = 0; } for (i = 0; i < arr.length; i++) { count[arr[i]]++; } for (i = min; i <= max; i++) { while (count[i]-- > 0) { arr[z++] = i; ...
code/sorting/src/counting_sort/counting_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // counting_sort.m // Created by DaiPei on 2017/10/15. // #import <Foundation/Foundation.h> @interface CountingSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation CountingSort - (void)sort:(NSMutableArray<NSNumber *> *)array { ...
code/sorting/src/counting_sort/counting_sort.py
# Part of Cosmos by OpenGenus Foundation # Python program for counting sort # The main function that sort the given string arr[] in # alphabetical order def count_sort(arr): # The output character array that will have sorted arr output = [0 for i in range(256)] # Create a count array to store count of i...
code/sorting/src/counting_sort/counting_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // counting_sort.swift // Created by DaiPei on 2017/10/15. // import Foundation func countingSort(_ 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 { ma...
code/sorting/src/cycle_sort/README.md
# Cycle Sort Cycle sort is an in-place, unstable sorting algorithm, a comparison sort that is theoretically optimal in terms of the total number of writes to the original array, unlike any other in-place sorting algorithm. It is based on the idea that array to be sorted can be divided into cycles. Cycles can be visua...
code/sorting/src/cycle_sort/cycle_sort.c
#include <stdio.h> void swap(int *a, int *b) { int t = *b; *b = *a; *a = t; } void cycleSort(int arr[], int n) { int cycle_start; for (cycle_start = 0; cycle_start <= n - 2; ++cycle_start) { int item = arr[cycle_start]; int pos = cycle_start; int i; for (i = cy...
code/sorting/src/cycle_sort/cycle_sort.cpp
// C++ program to impleament cycle sort #include <iostream> #include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation // Function sort the array using Cycle sort void cycleSort (vector<int>& arr) { // traverse array elements and put it to on // the right place for (size_t cycle_start ...
code/sorting/src/cycle_sort/cycle_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 array = Enumerable.Range(1, 20).Select(x => random.Next(1,40)).ToArray(); Console.WriteLine("Unsorted"); Console.WriteL...
code/sorting/src/cycle_sort/cycle_sort.go
package main import ( "fmt" ) // Part of Cosmos by OpenGenus Foundation func main() { arr := []int{1, 6, 4, 7, 2, 8} fmt.Printf("Before sort: %v\n", arr) CycleSort(&arr) fmt.Printf("After sort: %v\n", arr) } func CycleSort(arr *[]int) int { writes := 0 // Loop through the array to find cycles to rotate. for...
code/sorting/src/cycle_sort/cycle_sort.java
// Java program to impleament cycle sort // Part of Cosmos by OpenGenus Foundation import java.util.*; import java.lang.*; class CycleSort { // Function sort the array using Cycle sort public static void cycleSort (int arr[], int n) { // count number of memory writes int writes = 0; ...
code/sorting/src/cycle_sort/cycle_sort.js
/** * Cycle Sort Implementation in JavaScript * * @author Ahmar Siddiqui <ahmar.siddiqui@gmail.com> * @github @ahhmarr * @date 07/Oct/2017 * Part of Cosmos by OpenGenus Foundation */ const cycleSort = array => { // last record will already be in place for (let start = 0; start < array.length - 1; start++...
code/sorting/src/cycle_sort/cycle_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // cycle_sort.m // Created by DaiPei on 2017/10/15. // #import <Foundation/Foundation.h> @interface CycleSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation CycleSort - (void)sort:(NSMutableArray<NSNumber *> *)array { for (i...
code/sorting/src/cycle_sort/cycle_sort.py
# Part of Cosmos by OpenGenus Foundation def cycle_sort(arr): writes = 0 # Loop through the array to find cycles for cycle in range(0, len(arr) - 1): item = arr[cycle] # Find the location to place the item pos = cycle for i in range(cycle + 1, len(arr)): if ar...
code/sorting/src/cycle_sort/cycle_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // cycle_sort.swift // Created by DaiPei on 2017/10/15. // import Foundation func cycleSort(_ array: inout [Int]) { for cycleStart in 0..<array.count { var value = array[cycleStart] var pos = cycleStart // count all smaller elemen...
code/sorting/src/flash_sort/README.md
# Flash sort Flash sort is a distribution sorting algorithm. It has a usual performance of O(n) for uniformly distributed data sets. It has relatively less memory requirement. The basic idea behind flashsort is that in a data set with a known distribution, it is easy to immediately estimate where an element should be ...
code/sorting/src/flash_sort/flash_sort.c
// The flash sort algorithm // The idea is simple // If we know min max of arr is 0 and 100 // We know that 50 must be somewhere near the mid #include <stdio.h> #include <stdlib.h> void myswap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void flashSort(int *arr, int size) { // Phase 1 in...
code/sorting/src/flash_sort/flash_sort.js
"use strict"; function flash_sort(arr) { let max = 0; let min = arr[0]; const n = arr.length; const m = ~~(0.45 * n); const l = new Array(m); for (var i = 1; i < n; ++i) { if (arr[i] < min) { min = arr[i]; } if (arr[i] > arr[max]) { max = i; } } if (min === arr[max]) { ...
code/sorting/src/flash_sort/flash_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // flash_sort.m // Created by DaiPei on 2017/10/17. // #import <Foundation/Foundation.h> @interface FlashSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation FlashSort - (void)sort:(NSMutableArray<NSNumber *> *)array { // fi...
code/sorting/src/flash_sort/flash_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // flash_sort.swift // Created by DaiPei on 2017/10/17. // import Foundation func flashSort(_ array: inout [Int]) { // find the max and min item var max = Int.min var min = Int.max for item in array { if item > max { max = item ...
code/sorting/src/gnome_sort/README.md
# Gnome Sort Gnome sort (or Stupid sort) is a sorting algorithm which is similar to insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in bubble sort. Gnome Sort is based on the technique used by the standard Dutch Garden Gnome, i.e., how he sorts a line of flowe...
code/sorting/src/gnome_sort/gnome_sort.c
#include <stdio.h> void swap(int *a, int *b) { int t = *a; *a = *b; *b = t; } void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) ++index; if (arr[index] >= arr[index - 1]) ++index; else { swap(&arr[index], ...
code/sorting/src/gnome_sort/gnome_sort.cpp
// A C++ Program to implement Gnome Sort #include <iostream> using namespace std; // A function to sort the algorithm using gnome sort void gnomeSort(int arr[], int n) { int index = 0; while (index < n) { if (index == 0) index++; if (arr[index] >= arr[index - 1]) in...
code/sorting/src/gnome_sort/gnome_sort.go
package main import ( "fmt" ) // Gnome Sort in Golang // Part of Cosmos by OpenGenus Foundation // GnomeSort sorts the given slice func GnomeSort(a []int) { pos := 0 for pos < len(a) { if pos == 0 || a[pos] >= a[pos-1] { pos++ } else { a[pos], a[pos-1] = swap(a[pos], a[pos-1]) pos-- } } } func sw...
code/sorting/src/gnome_sort/gnome_sort.java
// Java Program to implement Gnome Sort import java.util.Arrays; public class GnomeSort { private static void gnomeSort(int arr[]) { int index = 0; while (index < arr.length) { if ((index == 0) || (arr[index - 1] <= arr[index])) { index++; } else { ...
code/sorting/src/gnome_sort/gnome_sort.js
function gnomeSort(arr) { let index = 0; while (index <= arr.length) { if (index > 0 && arr[index - 1] > arr[index]) { let tmp = arr[index]; arr[index] = arr[index - 1]; arr[index - 1] = tmp; --index; } else { --index; } } } // test case const a = [3, 6, 2, 9, 8, 1, 4, ...
code/sorting/src/gnome_sort/gnome_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // gnome_sort.m // Created by DaiPei on 2017/10/16. // #import <Foundation/Foundation.h> @interface GnomeSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation GnomeSort - (void)sort:(NSMutableArray<NSNumber *> *)array { if (ar...
code/sorting/src/gnome_sort/gnome_sort.py
# Python program to implement Gnome Sort # A function to sort the given list using Gnome sort def gnome_sort(arr, n): index = 0 while index < n: if index == 0: index = index + 1 if arr[index] >= arr[index - 1]: index = index + 1 else: arr[index], ar...
code/sorting/src/gnome_sort/gnome_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // gnome_sort.swift // Created by DaiPei on 2017/10/16. // import Foundation func gnomeSort(_ array: inout [Int]) { if array.count <= 1 { return } var index = 1 while index < array.count { if index == 0 { index += 1 ...
code/sorting/src/heap_sort/README.md
# Heap Sort Heap sort is a comparison based, simple and efficient sorting algorithm. There are two main parts to the process: * A heap is built from the unsorted data. The algorithm separates the unsorted data from the sorted data. * The largest element from the unsorted data is moved into an array Thus, Heap Sort use...
code/sorting/src/heap_sort/heap_sort.c
// C implementation of Heap Sort // Part of Cosmos by OpenGenus Foundation #include <stdio.h> #include <stdlib.h> // A heap has current size and array of elements struct MaxHeap { int size; int* array; }; // A utility function to swap to integers void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } //...
code/sorting/src/heap_sort/heap_sort.cpp
/* Part of Cosmos by OpenGenus Foundation */ #include <vector> #include <iostream> using namespace std; void heapify (vector<int> &v, int n, int i) { int largest = i; int l = 2 * i + 1; int r = 2 * i + 2; if (l < n && v[l] > v[largest]) largest = l; if (r < n && v[r] > v[largest]) ...
code/sorting/src/heap_sort/heap_sort.cs
using System; using System.Collections.Generic; namespace CS { /* Part of Cosmos by OpenGenus Foundation */ class MergeSort { private static int ParentIndex(int index) { return (index - 1) / 2; } private static int LeftChildIndex(int index) { ...
code/sorting/src/heap_sort/heap_sort.go
/* Part of Cosmos by OpenGenus Foundation */ package main import "fmt" type MaxHeap struct { data []int } func swap(x, y int) (int, int) { return y, x } func (h *MaxHeap) Insert(value int) { h.data = append(h.data, value) index := len(h.data) - 1 parent := (index - 1) / 2 for index > 0 && h.data[index] < h.da...
code/sorting/src/heap_sort/heap_sort.java
import java.util.*; /* * Part of Cosmos by OpenGenus Foundation */ public class HeapSort { public static void main(String[] args) { // array used for testing int[] a = {5, 11, 1234, 2, 6}; System.out.println(Arrays.toString(a)); sort(a); System.out.println(Arrays.toStri...
code/sorting/src/heap_sort/heap_sort.js
/* * Part of Cosmos by OpenGenus Foundation */ var arrayLength; function heap_root(inputArray, i) { var left = 2 * i + 1; var right = 2 * i + 2; var max = i; if (left < arrayLength && inputArray[left] > inputArray[max]) { max = left; } if (right < arrayLength && inputArray[right] > inputArray[max]...
code/sorting/src/heap_sort/heap_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // heap_sort.m // Created by DaiPei on 2017/10/9. // #import <Foundation/Foundation.h> @interface HeapSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation HeapSort - (void)sort:(NSMutableArray<NSNumber *> *)array { int n = (i...
code/sorting/src/heap_sort/heap_sort.py
# Part of Cosmos by OpenGenus Foundation import math def heap_root(arr, i, length): left = 2 * i + 1 right = 2 * i + 2 max_index = i if left < length and arr[left] > arr[max_index]: max_index = left if right < length and arr[right] > arr[max_index]: max_index = right if max_...
code/sorting/src/heap_sort/heap_sort.rb
# Part of Cosmos by OpenGenus Foundation class Array def heap_sort heapify the_end = length - 1 while the_end > 0 self[the_end], self[0] = self[0], self[the_end] the_end -= 1 sift_down(0, the_end) end self end def heapify # the_start is the last parent node the_sta...
code/sorting/src/heap_sort/heap_sort.rs
// Part of Cosmos by OpenGenus Foundation fn heapify(arr: &mut [i32], n: usize, i: usize){ let mut largest = i; //largest as root let l = 2*i + 1; //left let r = 2*i + 2; //right //if child larger than root if l < n && arr[l as usize] > arr[largest as usize]{ largest = l; } //if c...
code/sorting/src/heap_sort/heap_sort.sc
object heapsort { def left(i: Int) = (2*i) + 1 def right(i: Int) = left(i) + 1 def parent(i: Int) = (i - 1) / 2 def swap(a: Array[Int], i: Int, j: Int): Unit = { val t = a(i) a(i) = a(j) a(j) = t } def maxHeap (a...
code/sorting/src/heap_sort/heap_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // heap_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func heapSort(_ array: inout [Int]) { // create heap for i in stride(from: array.count / 2, to: -1, by: -1) { sink(array: &array, at: i, to: array.count - 1) } // sort...
code/sorting/src/heap_sort/heapsort.go
package main import "fmt" import "math/rand" import "time" type MaxHeap struct { slice []int heapSize int } func BuildMaxHeap(slice []int) MaxHeap { h := MaxHeap{slice: slice, heapSize: len(slice)} for i := len(slice) / 2; i >= 0; i-- { h.MaxHeapify(i) } return h } func (h MaxHeap) MaxHeapify(i int) { l...
code/sorting/src/insertion_sort/README.md
# Insertion Sort Insertion sort iterates through an array by taking one input element at each iteration, and grows a sorted output. With each iteration, insertion sorts removes the element at the current index, finds its correct position in the sorted output list, and inserts it there. This is repeated until no element...
code/sorting/src/insertion_sort/insertion_sort.c
/* Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> typedef int bool; void insertionSort(int*, int, bool); void printArray(int*, int); int main() { int n; /* Taking number of array elements as input from user */ printf("Enter size of array:\n"); scanf("%d", &n); int arr[n]; /* Taking arr...
code/sorting/src/insertion_sort/insertion_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * insertion sort synopsis * * template<typename _Bidirectional_Iter, typename _Compare> * void * insertionSort(_Bidirectional_Iter begin, _Bidirectional_Iter end, _Compare compare); * * template<typename _Bidirectional_Iter> * void * insertionSort(_Bidirectional_...
code/sorting/src/insertion_sort/insertion_sort.cs
/* * C# Program to Perform Insertion Sort */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int[] arr = new int[5] { 83, 12, 3, 34, 60 }; ...
code/sorting/src/insertion_sort/insertion_sort.dart
main() { print(insertionSort([8, 9, 4, 2, 6, 10, 12])); } List<int> insertionSort(List<int> list) { for (int j = 1; j < list.length; j++) { int key = list[j]; int i = j - 1; while (i >= 0 && list[i] > key) { list[i + 1] = list[i]; i = i - 1; list[i + 1] = key; } } return list;...
code/sorting/src/insertion_sort/insertion_sort.go
package main import ( "fmt" ) // Part of Cosmos by OpenGenus Foundation func main() { array := []int{9, 6, 7, 3, 2, 4, 5, 1} insertion(array) } func insertion(array []int) { lenght := len(array) for i := 1; i < lenght; i++ { j := i for j > 0 && array[j-1] > array[j] { array[j-1], array[j] = array[j], ...
code/sorting/src/insertion_sort/insertion_sort.hs
{- Part of Cosmos by OpenGenus Foundation -} insertion_sort :: Ord a => [a] -> [a] insertion_sort [] = [] insertion_sort [x] = [x] insertion_sort (x:arrx) = insert $ insertion_sort arrx where insert [] = [x] insert (y:arry) | x < y = x : y : arry | otherwise = y : insert a...
code/sorting/src/insertion_sort/insertion_sort.java
// Part of Cosmos by OpenGenus Foundation class InsertionSort { void sort(int arr[]) { // sort() performs the insertion sort on the array which is passed as argument from main() for (int i = 0; i < arr.length; ++i) { for (int j = i; j > 0 && arr[j - 1] > arr[j]; j--) { // swapping...
code/sorting/src/insertion_sort/insertion_sort.js
// 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 + 1] = temp; } return array; } // insertio...
code/sorting/src/insertion_sort/insertion_sort.kt
import java.util.* fun <T : Comparable<T>> insertionsort(items : MutableList<T>) : List<T> { if (items.isEmpty()) { return items } for (count in 1..items.count() - 1) { val item = items[count] var i = count while (i>0 && item < items[i - 1]) { ite...
code/sorting/src/insertion_sort/insertion_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // insertion_sort.m // Created by DaiPei on 2017/10/9. // #import <Foundation/Foundation.h> @interface InsertionSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *) array; @end @implementation InsertionSort - (void)sort:(NSMutableArray<NSNumber *> *)array ...
code/sorting/src/insertion_sort/insertion_sort.ml
(* Part of Cosmos by OpenGenus Foundation *) let rec sort = function | [] -> [] | hd :: tl -> insert hd (sort tl) and insert x = function | [] -> [x] | hd :: tl -> if x < hd then x :: hd :: tl else hd :: insert x tl ;; sort [];; sort [1];; sort [1; 2];; sort [2; 1];; sort [4; 3; 2; 1];; sort [2; 5; 4; 3; 1];;
code/sorting/src/insertion_sort/insertion_sort.php
<?php // Part of Cosmos by OpenGenus Foundation $array = array(0,1,6,7,6,3,4,2); function insert_sort($array) { for($i = 0; $i < count($array); $i++) { $val = $array[$i]; $j = $i-1; while($j >= 0 && $array[$j] > $val) { $array[$j+1] = $array[$j]; $j--; } $array[$j+1] = $val; }...
code/sorting/src/insertion_sort/insertion_sort.py
""" Part of Cosmos by OpenGenus Foundation Program for InsertionSort sorting """ def insertion_sort(L): length = len(L) for i in range(length): key = L[i] j = i - 1 while j >= 0 and key < L[j]: L[j + 1] = L[j] j -= 1 L[j + 1] = key return L if __n...
code/sorting/src/insertion_sort/insertion_sort.rb
# Part of Cosmos by OpenGenus Foundation def insertion_sort(arr) n = arr.length i = 1 while i < n key = arr[i] j = i - 1 while (j >= 0) && (key < arr[j]) arr[j + 1] = arr[j] j -= 1 end arr[j + 1] = key i += 1 end arr end arr = [3, 1, 5, 8, 11, 10, 23, 24, -1] puts "U...
code/sorting/src/insertion_sort/insertion_sort.re
let rec sort = fun | [] => [] | [hd, ...tl] => insert(hd, sort(tl)) and insert = x => fun | [] => [x] | [hd, ...tl] => if (x < hd) { [x, hd, ...tl]; } else { [hd, ...insert(x, tl)]; };
code/sorting/src/insertion_sort/insertion_sort.rs
// Part of Cosmos by OpenGenus Foundation fn insertion_sort(array_A: &mut [int, ..6]) { // Implementation of the traditional insertion sort algorithm in Rust // The idea is to both learn the language and re visit classic (and not so much) // algorithms. // This algorithm source has been extracted from "Introductio...
code/sorting/src/insertion_sort/insertion_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/insertion_sort/insertion_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // insertion_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func insertionSort(_ array: inout [Int]) { for i in 1..<array.count { var j = Int(i) let key = array[j] while j >= 1 && key < array[j - 1] { array...
code/sorting/src/insertion_sort/insertion_sort_extension.swift
/* Part of Cosmos by OpenGenus Foundation */ import Foundation extension Array { mutating func insertionSort(compareWith less: (Element, Element) -> Bool) { if self.count <= 1 { return } for i in 1..<self.count { var j = Int(i) let key = self[j] ...
code/sorting/src/intro_sort/README.md
# Intro Sort Introsort or introspective sort is the best sorting algorithm around. It is a **hybrid sorting algorithm** and thus uses three sorting algorithm to minimise the running time, i.e., **Quicksort, Heapsort and Insertion Sort**. ## Explanation Introsort begins with quicksort and if the recursion depth goes mo...
code/sorting/src/intro_sort/intro_sort.cpp
#include <cmath> #include <algorithm> #include <iostream> using namespace std; void introsort_r(int a[], int first, int last, int depth); void _introsort(int a[], int n); int _partition(int a[], int first, int last); void _insertion(int a[], int n); void _swap(int *a, int *b); void _doheap(int a[], int begin, int end);...
code/sorting/src/intro_sort/intro_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // intro_sort.m // Created by DaiPei on 2017/10/22. // #import <Foundation/Foundation.h> @interface IntroSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation IntroSort - (void)sort:(NSMutableArray<NSNumber *> *)array { [self ...
code/sorting/src/intro_sort/intro_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // intro_sort.swift // Created by DaiPei on 2017/10/21. // import Foundation func introSort(_ array: inout [Int]) { introSortCore(&array, from: 0, to: array.count - 1, depth: Int(2 * log(Double(array.count)))); } private func introSortCore(_ array: inout [Int], ...
code/sorting/src/median_sort/median_sort.cpp
#include <iostream> using namespace std; // Part of Cosmos by OpenGenus Foundation void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int Partition(int a[], int low, int high) { int pivot, index, i; index = low; pivot = high; for (i = low; i < high; i++) i...
code/sorting/src/median_sort/median_sort.cs
/* Part of Cosmos by OpenGenus Foundation */ using System; namespace CS { public class MedianSort { static void swap(ref int a, ref int b) { int temp = a; a = b; b = temp; } static int SelectPivotIndex(int[] arr, int right, int left) { ...
code/sorting/src/median_sort/median_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // median_sort.m // Created by DaiPei on 2017/10/27. // #import <Foundation/Foundation.h> @interface MedianSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation MedianSort - (void)sort:(NSMutableArray<NSNumber *> *)array { [se...
code/sorting/src/median_sort/median_sort.py
# Part of Cosmos by OpenGenus Foundation def median_sort(list): data = sorted(list) n = len(data) if n == 0: return None if n % 2 == 1: return data[n // 2] else: i = n // 2 return (data[i - 1] + data[i]) / 2 # list = [0,2,3,4,5,6,7,8,9] # print calculateMedian(list)...
code/sorting/src/median_sort/median_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // median_sort.swift // Created by DaiPei on 2017/10/25. // import Foundation func medianSort(_ array: inout [Int]) { recursiveMediaSort(&array, left: 0, right: array.count - 1) } private func recursiveMediaSort(_ array: inout [Int], left: Int, right: Int) { ...
code/sorting/src/median_sort/median_sort_fast.cpp
#include <vector> using namespace std; // Part of Cosmos by OpenGenus Foundation int selectPivotIndex(const vector<int>& A, const int left, const int right) { const int mid = (left + right) / 2; // median of three if (A[left] > A[mid]) // this is really insertion sort { if (A[left] > A[right]) ...
code/sorting/src/merge_sort/README.md
# Merge Sort The merge sort is a comparison-based sorting algorithm. This algorithm works by dividing the unsorted list into n sublists; each one containing one element (which is considered sorted, since it only has one element). Then it merges the sublists to produce new sorted sublists, this is repeated until there'...
code/sorting/src/merge_sort/merge_sort.c
/* * Part of Cosmos by OpenGenus Foundation */ #include <stdio.h> typedef int bool; /* Merges two subhalves of a[]. First sub-half is a[low..mid] Second sub-half is a[mid+1..high] */ void merging (int a[], int b[], int low, int mid, int high, bool order) { int l1, l2, i; /* Order 1 for sorti...
code/sorting/src/merge_sort/merge_sort.cpp
/* * Part of Cosmos by OpenGenus Foundation * * merge sort synopsis * * namespace merge_sort_impl { * template<typename _Random_Acccess_Iter> * _Random_Acccess_Iter * advance(_Random_Acccess_Iter it, std::ptrdiff_t n); * } // merge_sort_impl * * template<typename _Random_Acccess_Iter, typename _Compare> * v...
code/sorting/src/merge_sort/merge_sort.cs
using System; using System.Collections.Generic; namespace CS { /* Part of Cosmos by OpenGenus Foundation */ class MergeSort { private static int[] SortInternal(int[] arr, int start, int count) { // Base case - 0 or 1 elements if (count == 1) { ...
code/sorting/src/merge_sort/merge_sort.fs
//Part of Cosmos by OpenGenus Foundation open System open System.Collections.Generic let rec merge (left:IComparable list) (right:IComparable list): IComparable list = match (left,right) with | (_,[]) -> left | ([],_) -> right | (l::ls,r::rs) when l < r -> l::merge ls right | (l::ls,r::rs) -> r::...
code/sorting/src/merge_sort/merge_sort.go
package main import ( "fmt" ) func main() { A := []int{3, 5, 1, 6, 1, 7, 2, 4, 5} fmt.Println(sort(A)) } // top-down approach func sort(A []int) []int { if len(A) <= 1 { return A } left, right := split(A) left = sort(left) right = sort(right) return merge(left, right) } ...
code/sorting/src/merge_sort/merge_sort.hs
-- Part of Cosmos by OpenGenus Foundation split_list::[a]->([a],[a]) split_list x = splitAt (div (length x) $ 2) x merge_sort::Ord a=>[a]->[a] merge_sort x | length x == 0 = [] | length x == 1 = x | length x > 1 = merge (merge_sort left) (merge_sort right) where (left,right)=split_list x mer...
code/sorting/src/merge_sort/merge_sort.java
/* Java program for Merge Sort */ // Part of Cosmos by OpenGenus Foundation class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] private void merge(int arr[], int l, int m, int r) { // Find sizes of two subarrays to be merged ...
code/sorting/src/merge_sort/merge_sort.js
var a = [34, 203, 3, 746, 200, 984, 198, 764, 9]; // Part of Cosmos by OpenGenus Foundation function mergeSort(arr) { if (arr.length < 2) return arr; var middle = parseInt(arr.length / 2); var left = arr.slice(0, middle); var right = arr.slice(middle, arr.length); return merge(mergeSort(left), mergeSort(rig...
code/sorting/src/merge_sort/merge_sort.kt
import java.util.* fun <T : Comparable<T>>mergesort(items : MutableList<T>) : MutableList<T> { if (items.isEmpty()) { return items } fun merge(left : MutableList<T>, right : MutableList<T>) : MutableList<T> { var merged : MutableList<T> = arrayListOf<T>() while(!left.isEmpty() && !...
code/sorting/src/merge_sort/merge_sort.m
/* Part of Cosmos by OpenGenus Foundation */ // // merge_sort.m // Created by DaiPei on 2017/10/10. // #import <Foundation/Foundation.h> @interface MergeSort : NSObject - (void)sort:(NSMutableArray<NSNumber *> *)array; @end @implementation MergeSort - (void)sort:(NSMutableArray<NSNumber *> *)array { [self ...
code/sorting/src/merge_sort/merge_sort.php
<?php function merge_sort($my_array){ if(count($my_array) == 1 ) return $my_array; $mid = count($my_array) / 2; $left = array_slice($my_array, 0, $mid); $right = array_slice($my_array, $mid); $left = merge_sort($left); $right = merge_sort($right); return merge($left, $right); } function merge($left, $righ...
code/sorting/src/merge_sort/merge_sort.pl
%National University from Colombia %Author:Andres Vargas, Jaime %Gitub: https://github.com/jaavargasar %webpage: https://jaavargasar.github.io/ %Language: Prolog % Merge Sort llist([],0). llist([_|T],N):- llist(T,NT),N is NT +1. divHalf(List,A,B) :- llsplit(List,List,A,B). llsplit(S,[],[],S). llsplit(S,[_],[],S). l...
code/sorting/src/merge_sort/merge_sort.py
# Part of Cosmos by OpenGenus Foundation # Split array in half, sort the 2 halves and merge them. # When merging we pick the smallest element in the array. # The "edge" case is when one of the arrays has no elements in it # To avoid checking and breaking the look, finding which array has elements and then # Starting a...
code/sorting/src/merge_sort/merge_sort.rb
# Part of Cosmos by OpenGenus Foundation def merge(a, l, m, r) n1 = m - l + 1 left = Array.new(n1) # Created temp array for storing left subarray n2 = r - m right = Array.new(n2) # Created temp array for storing right subarray for i in 0...n1 # Copy values from left subarray to temp array left[i] = a[l +...
code/sorting/src/merge_sort/merge_sort.rs
// Part of Cosmos by OpenGenus Foundation /// A program that defines an unsorted vector, /// and sorts it using a merge sort implementation. fn main() { let mut arr = vec![4, 5, 9, 1, 3, 0, 7, 2, 8]; merge_sort(&mut arr); println!("Sorted array: {:?}", arr) } /// Sort the given array using merge sort. //...
code/sorting/src/merge_sort/merge_sort.scala
object Main { def merge(left: List[Int], right: List[Int]): List[Int] = { if (left.isEmpty) { return right } else if (right.isEmpty) { return left } if (left.head < right.head) { return left.head :: merge(left.tail, right) } else { return right.h...
code/sorting/src/merge_sort/merge_sort.sh
#!/bin/bash # code for merge sort in shell script. declare -a array ARRAYSZ=10 create_array() { i=0 while [ $i -lt $ARRAYSZ ]; do array[${i}]=${RANDOM} i=$((i+1)) done } merge() { local first=2 local second=$(( $1 + 2 )) for i in ${@:2} do if [[ $first -eq $(( $1 + 2 )) ]]...
code/sorting/src/merge_sort/merge_sort.swift
/* Part of Cosmos by OpenGenus Foundation */ // // merge_sort.swift // Created by DaiPei on 2017/10/11. // import Foundation func mergeSort(_ array: inout [Int]) { mergeSort(&array, low:0, high: array.count - 1) } private func mergeSort(_ array: inout [Int], low: Int, high: Int) { if low < high { ...
code/sorting/src/merge_sort/merge_sort.ts
// Part of Cosmos by OpenGenus Foundation export default function MergeSort(items: number[]): number[] { return divide(items); } function divide(items: number[]): number[] { var halfLength = Math.ceil(items.length / 2); var low = items.slice(0, halfLength); var high = items.slice(halfLength); if (...