-9
\$\begingroup\$

There is an array of integer values to be sorted.During the sorting process, the places of two numbers can be interchanged. Each interchange has a cost, which is the sum of the two numbers involved.

You must write a program that determines the minimal cost to sort the sequence of numbers.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ First of all please read the faq. Your puzzle should have an objective primary winning criterion. Have a look around to see many well-specified questions. You may also read the comments below your last puzzle as those also address the same questions. \$\endgroup\$
    – Howard
    Commented May 6, 2012 at 8:03
  • 2
    \$\begingroup\$ We *must*? You should change site... \$\endgroup\$
    – rubik
    Commented May 6, 2012 at 12:04
  • \$\begingroup\$ Are the integers equally distributed, or normal distributed, or somehow else? How many of them and how big? Do you have some sample input, something like for i in {1..100}; do echo $((RANDOM%256)); done for example. \$\endgroup\$ Commented May 27, 2012 at 21:20
  • \$\begingroup\$ They are not equally distrubuted \$\endgroup\$ Commented May 28, 2012 at 4:31

1 Answer 1

7
\$\begingroup\$

Scala:

def minimalCostToSortArray (daArray: Array[Int]) = 0

Why is the cost always zero? Because I don't change numbers at all:

def arrsort (a: Array[Int], pos:Int = 0): Array[Int] = {
  if (pos >= a.length -1) a else { 
    if (a(pos) > a(pos+1)) {
      val diff = a(pos) - a(pos+1)
      a (pos) -= diff
      a (pos+1) += diff
      arrsort (a)
    } else arrsort (a, pos+1) 
  } 
}
\$\endgroup\$
2
  • 3
    \$\begingroup\$ For the challenge to make sense at all, I'd interpret it as saying that the only operation we're allowed to use to modify the array is swapping two numbers. Still, +1 for thinking outside the box (and -1 for cheating, which leaves the total at ±0). \$\endgroup\$ Commented May 6, 2012 at 22:34
  • 1
    \$\begingroup\$ I read ... the places can be interchanged as optional, but more so, as badly prepared question. I understand my answer more as a criticism on a badly prepared question. \$\endgroup\$ Commented May 6, 2012 at 22:49

Not the answer you're looking for? Browse other questions tagged or ask your own question.