Answer the question
In order to leave comments, you need to log in
Create a new array for the new values, or change the values of the old array?
Hello.
In the book about algorithms (Groaking Algorithms) there is an example of creating an array sorting function (selection sort). In the book, the body of the sort function uses two variables and two arrays (One incoming unsorted and one outgoing sorted).
I made the function a bit my own way and refrained from creating a new array i.e. I decided to perform all replacement operations simply with the help of variables.
My code with one array:
package main
import (
"fmt"
"time"
)
func pleaseSortMeNumbers(n []int) []int {
counter := 0
fmt.Println("Sorting algorithm started...")
for i := range n {
lowestNumber := n[i]
lowestNumberId := i
for j := i; j <= len(n)-1; j++ {
if lowestNumber > n[j] {
lowestNumber = n[j]
lowestNumberId = j
}
counter++
}
n[lowestNumberId] = n[i]
n[i] = lowestNumber
}
time.Sleep(time.Second / 2)
fmt.Println("Sorting done!")
time.Sleep(time.Second / 2)
fmt.Println(counter, " comparisons.")
time.Sleep(time.Second / 2)
fmt.Println("Slice: ", n)
return n
}
Answer the question
In order to leave comments, you need to log in
Your code implements in-place sorting (in place). This method allows you to change the data in the input array (in fact, you have a slice in your code) and not return it from the function, but simply use it further after calling the sort function.
In general, your reasoning is correct, because. allocating space for an array is always an expensive operation. But your sorting method is not always applicable. Sometimes it is necessary to keep the original array intact.
According to the code itself, it is not very clear why Sleep is used. I
advise you to name arrays\slices more meaningfully, for example, arr
orsrc
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question