Scala vs Java : Implementing quicksort — not optimized

Below is an implementation of a quicksort the java way

void sort(int[] xs) {
sort(xs, 0, xs.length -1 );
}
void sort(int[] xs, int l, int r) {
int pivot = xs[(l+r)/2];
int a = l; int b = r;
while (a <= b)
while (xs[a] < pivot) { a = a + 1; }
while (xs[b] > pivot) { b = b – 1; }
if (a <= b) {
swap(xs, a, b);
a = a + 1;
b = b – 1;
}
}
if (l < b) sort(xs, l, b);
if (b < r) sort(xs, a, r);
}
void swap(int[] arr, int i, int j) {
int t = arr[i]; arr[i] = arr[j]; arr[j] = t;
}
Quicksort the scala way ... looks neater and is easier to understand

object QuickSort {
def sort(xs:Array[Int]):Array[Int]={
if(xs.length<1)xs
else{
val pivot=xs(xs.length/2)
Array.concat(
sort(xs filter (pivot >)),
xs filter (pivot ==),
sort(xs filter (pivot <)))
}
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: