Thursday, May 19, 2011

Evaluating Test Cases for the Sort Function

Evaluating whether a sort function is doing a good job is difficult. First of all, I can't tell what the compiler is going to do with my code. The same or similar high-level code in different languages could be very different in implementation.

Second, different parts of the code take up different amounts of resources. Reading and comparing values takes a certain amount of cycles, swapping takes a certain amount, and so forth.

Still, we should be able to figure out something to say about how much wheel spinning is necessary for each kind of sort.

I'm going to insert 2 count variables:

  • $countCompares01
  • $countSwaps01

These will have to be global variables. This is not part of the functional programming exercise. Since I want to look at how things are working, I don't care if I do it by looking at side-effects.

Here's the body of the bubble sort script block:

param ($sourceArray) # Takes any array - not tested for mixed arrays (strings and ints, for instance

$global:countCompares = 0 # values for testing compares and swaps.

$global:countSwaps = 0

for ($j = 0; $j -lt $sourceArray.length; $j++)

{

for ($i = 0; $i -lt ($sourceArray.length - 1); $i++) # checks each position against the position to its right

{

$global:countCompares++ # increment compares variable each time two values are compared

if ($sourceArray[$i] -gt $sourceArray[$i+1]) # uses Greater Than.

{

$global:countSwaps++ # increment swaps variable each time two values are swapped.

$temp = $sourceArray[$i] #swap if necessary.

$sourceArray[$i] = $sourceArray[$i+1]

$sourceArray[$i+1] = $temp

}

}

}

return $sourceArray # if none fail, then true

Here's the revised tests:

# Test Cases:


$testCase = 1..5

$testCase[0] = 1,2,3,4,5

$testCase[1] = 1,1,1,1,1

$testCase[2] = 1,2,3,4,3

$testCase[3] = 3,2,3,4,5

$testCase[4] = 3,2,3,4,3


foreach ($a in $testCase)

{

if (!(&$isSorted (&$bubble01 $a))) {"FAIL: List is sorted: $a"}

"Number of compares for $a is $global:countCompares."

"Number of swaps for $a is $global:countSwaps."

}

And here's the results:

PowerShell: .\tests

Number of compares for 1 2 3 4 5 is 20.

Number of swaps for 1 2 3 4 5 is 0.

Number of compares for 1 1 1 1 1 is 20.

Number of swaps for 1 1 1 1 1 is 0.

Number of compares for 1 2 3 3 4 is 20.

Number of swaps for 1 2 3 3 4 is 1.

Number of compares for 2 3 3 4 5 is 20.

Number of swaps for 2 3 3 4 5 is 1.

Number of compares for 2 3 3 3 4 is 20.

Number of swaps for 2 3 3 3 4 is 2.


Next, we can start adding more sort functions.

No comments:

Post a Comment