Created
February 18, 2013 06:51
-
-
Save romansky/4975513 to your computer and use it in GitHub Desktop.
QuickSort + Median pivot selection, in Scala
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def findMedian (array :Array[Int], lpos: Int, rpos: Int) : (Int, Int) = { | |
val first : Int = array(lpos) | |
val last : Int = array(rpos) | |
val middle : Int = array( lpos + scala.math.floor((rpos-lpos)/2).toInt ) | |
if ((first > last && first < middle) || (first < last && first > middle)) (first,lpos) | |
else if ((last > first && last < middle) || (last < first && last > middle)) (last,rpos) | |
else if ((middle > first && middle < last)|| (middle < first && middle > last)) (middle, lpos + scala.math.floor((rpos-lpos)/2).toInt) | |
else { (first,lpos) } | |
} | |
def swap(A:Array[Int], pos1: Int, pos2: Int) { | |
val tmp = A(pos2) | |
A(pos2) = A(pos1) | |
A(pos1) = tmp | |
} | |
/* Main Method */ | |
def QuickSort (array : Array[Int], lpos: Int, rpos: Int): Int = | |
if (lpos < rpos) { | |
val pPos : Int = Partition(array, lpos, rpos) | |
QuickSort(array, lpos, pPos-1) | |
QuickSort(array, pPos +1, rpos) | |
} | |
} | |
def Partition (A: Array[Int], l: Int, r :Int) : Int = { | |
swap(A,l,findMedian(A,l,r)._2) | |
val p = A(l) | |
var i = l + 1 | |
for (j <- (l+1 to r)) { | |
if (A(j) < p) { | |
swap(A, i, j) | |
i += 1 | |
} | |
} | |
swap(A,i-1, l) | |
i-1 | |
} | |
val sortMe = Array( 2, 8, 9, 3, 7, 5, 10, 1, 6, 4 ) | |
QuickSort(sortMe, 0,sortMe.length -1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment