I am new to Go Language and trying to learn it by doing. tried with MergeSort but some how I am missing something and result is not as expected. I am pretty sure it has something to do with slices I am using.
converted equivalent python
code to go
python works but go code missed something (in terms of my understanding to slice may be)
working Python Code
def mergeSort(arr):
if len(arr) > 1:
# Finding the mid of the array
mid = len(arr)//2
# Dividing the array elements
L = arr[:mid]
# into 2 halves
R = arr[mid:]
# Sorting the first half
mergeSort(L)
# Sorting the second half
mergeSort(R)
i = j = k = 0
# Copy data to temp arrays L[] and R[]
while i < len(L) and j < len(R):
if L[i] < R[j]:
arr[k] = L[i]
i = 1
else:
arr[k] = R[j]
j = 1
k = 1
# Checking if any element was left
while i < len(L):
arr[k] = L[i]
i = 1
k = 1
while j < len(R):
arr[k] = R[j]
j = 1
k = 1
# Code to print the list
def printList(arr):
for i in range(len(arr)):
print(arr[i], end=" ")
print()
# Driver Code
arr = [457, 4, 0, 500, -8, 6, 5, -20, -93, 50, 5, 1, 6, 10, 54, 7, 13, 10, -5, 50, 500, 8, 4, -1, -99, 5, 0, 0, -899]
printList(mergeSort(arr))
Converted equivalent Go Code
package main
import "fmt"
func main() {
intArr := []int{457, 4, 0, 500, -8, 6, 5, -20, -93, 50, 5, 1, 6, 10, 54, 7, 13, 10, -5, 50, 500, 8, 4, -1, -99, 5, 0, 0, -899}
fmt.Println(mergeSort(intArr))
}
func mergeSort(arr []int) []int {
if len(arr) > 1 {
// Finding the mid of the array
mid := int(len(arr) / 2)
// Dividing the array elements
L := arr[:mid]
// into 2 halves
R := arr[mid:]
// Sorting the first half
mergeSort(L)
// Sorting the second half
mergeSort(R)
i, j, k := 0, 0, 0
// Copy data to temp arrays L[] and R[]
for i < len(L) && j < len(R) {
if L[i] < R[j] {
arr[k] = L[i]
i
} else {
arr[k] = R[j]
j
}
k
}
// Checking if any element was left
for i < len(L) {
arr[k] = L[i]
i
k
}
for j < len(R) {
arr[k] = R[j]
j
k
}
}
return arr
}
but output is from Go
code
[-899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899 -899]
CodePudding user response:
Array slicing does not allocate new arrays in go. L, R and arr refers to the same underlying array. You can use "copy" to deep clone the slice:
func mergeSort(arr []int) []int {
if len(arr) > 1 {
// Finding the mid of the array
mid := int(len(arr) / 2)
// Dividing the array elements
L := make([]int, mid)
copy(L, arr[:mid])
// into 2 halves
R := make([]int, len(arr)-mid)
copy(R, arr[mid:])
// Sorting the first half
mergeSort(L)
// Sorting the second half
mergeSort(R)
i, j, k := 0, 0, 0
// Copy data to temp arrays L[] and R[]
for i < len(L) && j < len(R) {
if L[i] < R[j] {
arr[k] = L[i]
i
} else {
arr[k] = R[j]
j
}
k
}
// Checking if any element was left
for i < len(L) {
arr[k] = L[i]
i
k
}
for j < len(R) {
arr[k] = R[j]
j
k
}
}
return arr
}