Skip to content

Commit

Permalink
Add Merge Sort
Browse files Browse the repository at this point in the history
  • Loading branch information
ua-nick committed Apr 4, 2018
1 parent 7da6d73 commit 7c3420c
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions .travis.yml
Expand Up @@ -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 ./;
45 changes: 45 additions & 0 deletions MergeSort/MergeSort.go
@@ -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)
}
25 changes: 25 additions & 0 deletions MergeSort/MergeSort_test.go
@@ -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()
}
}
}
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -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

Expand Down

0 comments on commit 7c3420c

Please sign in to comment.