Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

Scala: Recursive selection sort problem..[code]

  • 06-08-2011 1:08pm
    #1
    Registered Users, Registered Users 2 Posts: 2,236 ✭✭✭


    Hi Guys,

    I'm doing some revision for an upcoming repeat :( and i've run into a problem with the following recursive implementation of Selection Sort in Scala.

    For the most card this works but it doesn't seem to be swapping the first two values when they should be swapped. I'm sure it's pretty basic but my problem solving cap is a little rusty at this stage :mad:

    Any ideas greatly appreciated:
    object question3 {
      def main(args : Array[String]) : Unit =
      {
    	  var arr = Array(8,9,8,5,2,4,1,6,3,7,5,-1,5,0,99)
    	  arr = sort(arr, 0, 0, 0)
    	  
    	  println("RESULT:")
    	  arr.foreach(str=>print(str+","))
      }
      def sort(arr : Array[Int], n : Int, min : Int, j : Int): Array[Int] =
      {
    	  if(n == arr.length)
    	  {
    	 	  return arr
    	  }
    	  else
    	  {
    		  var j = n+1
    		  var min = n
    		  
    		  if(j < arr.length)
    		  {
    			  if(arr(j) < arr(min))
    			  {
    			      min = j  
    			  }
    			  sort(arr, n+1, min, j+1)
    		  }
    		  if(min != n)
    		  {
    		 	var t = arr(n)
    		 	arr(n) = arr(min)
    		 	arr(min) = t
    		  }
    		  sort(arr, n+1, min, j)
    	  }
      }
    }
    
    


Advertisement