Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

View marioeguiluz's full-sized avatar
🎯
Focusing

Mario Eguiluz marioeguiluz

🎯
Focusing
View GitHub Profile
@marioeguiluz
marioeguiluz / HeapSort.swift
Last active November 14, 2017 13:17
Heap Sort Swift
//Safe bounds check for Array
//http://stackoverflow.com/questions/25329186/safe-bounds-checked-array-lookup-in-swift-through-optional-bindings
extension Collection {
/// Returns the element at the specified index iff it is within bounds, otherwise nil.
subscript (safe index: Index) -> Iterator.Element? {
return index >= startIndex && index < endIndex ? self[index] : nil
}
}
//Helper function to exchange position in one array
@marioeguiluz
marioeguiluz / HeapSort.m
Created May 14, 2015 00:01
HeapSort Objective-C
////////////////HEAP SORT////////////////
int leftLeafIndex(int rootIndex){
int heapIndex = rootIndex+1;
return heapIndex*2-1;
}
int rightLeafIndex(int rootIndex){
int heapIndex = rootIndex+1;
return heapIndex*2+1-1;
}
@marioeguiluz
marioeguiluz / MergeSort.swift
Last active October 5, 2016 05:13
Merge Sort Swift
//Merge Sort
func mergeSort<T:Comparable>(_ unsortedArray:Array<T>)->Array<T>{
var unsortedArray = unsortedArray
if unsortedArray.count < 2 {
return unsortedArray
}
let pivot:Int = unsortedArray.count/2
let leftArray:Array<T> = Array(unsortedArray[0..<pivot])
let rightArray:Array<T> = Array(unsortedArray[pivot..<unsortedArray.count])
@marioeguiluz
marioeguiluz / MergeSort.m
Last active December 2, 2016 12:15
MergeSort Objective-C
////////////////MERGE SORT////////////////
NSArray* mergeArrays(NSArray* A, NSArray* B) {
NSMutableArray *orderedArray = [NSMutableArray new];
long indexLeft = 0;
long indexRight = 0;
while (indexLeft < [A count] && indexRight < [B count]) {
if ([A[indexLeft] intValue] < [B[indexRight]intValue]) {
[orderedArray addObject:A[indexLeft++]];
}else if ([A[indexLeft] intValue] > [B[indexRight]intValue]){
@marioeguiluz
marioeguiluz / InsertionSort.swift
Last active September 21, 2016 00:49
Insertion Sort Swift
//Helper function to exchange position in one array
//From: http://stackoverflow.com/questions/24077880/swift-make-method-parameter-mutable
func exchange<T>(_ data: inout [T], i:Int, j:Int) {
let temp:T = data[i]
data[i] = data[j]
data[j] = temp
}
//Insertion Sort of an array of integers
func insertionSort<T:Comparable>(_ unsortedArray:Array<T>)->Array<T>{
@marioeguiluz
marioeguiluz / InsertionSort.m
Last active August 29, 2015 14:20
Insertion Sort Objective-C
//Insertion Sort of an array of integers
//**************************************
NSMutableArray* insertionSort(NSMutableArray* unsortedArray){
if(!unsortedArray) return nil;
if(unsortedArray.count<2) return unsortedArray;
for (int j=1; j<unsortedArray.count; j++) {
int i = j;
while(i>0 && [[unsortedArray objectAtIndex:(i-1)] intValue] > [[unsortedArray objectAtIndex:i] intValue])
{