I
I
Ilya2021-04-03 09:50:37
go
Ilya, 2021-04-03 09:50:37

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
}


An example of a code from a book with two arrays:
60681005f1c55891078390.png

In theory, in my implementation of the algorithm, space is occupied in memory for two variables and one array, and in the algorithm from the book, space is occupied in memory for two variables and two arrays. Are my reasoning correct or not? Is my algorithm better or worse?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-05-23
@hugga

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, arrorsrc

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question