Permalink
Browse files

Add Merge Sort

  • Loading branch information...
floyernick committed Apr 4, 2018
1 parent 7da6d73 commit 7c3420ceadde7104433ef481e95525db4035c3ea
Showing with 72 additions and 0 deletions.
  1. +1 −0 .travis.yml
  2. +45 −0 MergeSort/MergeSort.go
  3. +25 −0 MergeSort/MergeSort_test.go
  4. +1 −0 README.md
View
@@ -15,5 +15,6 @@ script:
cd ../InterpolationSearch && go test ./;
cd ../JumpSearch && go test ./;
cd ../LinearSearch && go test ./;
cd ../MergeSort && go test ./;
cd ../SelectionSort && go test ./;
cd ../TernarySearch && go test ./;
View
@@ -0,0 +1,45 @@
package MergeSort
func mergeParts(array []int, leftIndex, divideIndex, rightIndex int) {
var tempArray1, tempArray2 []int
for i := leftIndex; i <= divideIndex; i++ {
tempArray1 = append(tempArray1, array[i])
}
for i := divideIndex + 1; i <= rightIndex; i++ {
tempArray2 = append(tempArray2, array[i])
}
arrayIndex := leftIndex
tempArray1Index := 0
tempArray2Index := 0
for tempArray1Index != len(tempArray1) && tempArray2Index != len(tempArray2) {
if tempArray1[tempArray1Index] <= tempArray2[tempArray2Index] {
array[arrayIndex] = tempArray1[tempArray1Index]
tempArray1Index += 1
} else {
array[arrayIndex] = tempArray2[tempArray2Index]
tempArray2Index += 1
}
arrayIndex += 1
}
for tempArray1Index < len(tempArray1) {
array[arrayIndex] = tempArray1[tempArray1Index]
tempArray1Index += 1
arrayIndex += 1
}
for tempArray2Index < len(tempArray2) {
array[arrayIndex] = tempArray2[tempArray2Index]
tempArray2Index += 1
arrayIndex += 1
}
}
func MergeSort(array []int, leftIndex, rightIndex int) {
if leftIndex >= rightIndex {
return
}
divideIndex := int((leftIndex + rightIndex) / 2)
MergeSort(array, leftIndex, divideIndex)
MergeSort(array, divideIndex+1, rightIndex)
mergeParts(array, leftIndex, divideIndex, rightIndex)
}
@@ -0,0 +1,25 @@
package MergeSort
import (
"math/rand"
"sort"
"testing"
"time"
)
func TestSelectionSort(t *testing.T) {
random := rand.New(rand.NewSource(time.Now().UnixNano()))
array1 := make([]int, random.Intn(100-10)+10)
for i := range array1 {
array1[i] = random.Intn(100)
}
array2 := make(sort.IntSlice, len(array1))
copy(array2, array1)
MergeSort(array1, 0, len(array1)-1)
array2.Sort()
for i := range array1 {
if array1[i] != array2[i] {
t.Fail()
}
}
}
View
@@ -32,6 +32,7 @@ There are several data structures and algorithms implemented in this project. Th
- Comb Sort
- Cocktail Sort
- Gnome Sort
- Merge Sort
## Usage

0 comments on commit 7c3420c

Please sign in to comment.