Tuesday, May 17, 2011

A Bubble Sort Script Block

A couple of years back, I played with sort functions a bit – just the basics. What I wanted to do (and did, in part) was

  • Write a basic bubble sort.
  • Write variations on that sort that were – maybe – less “brute force”.
  • Evaluate whether different kinds of sort functions were better or worse compared to each other.

I could accomplish the first two goals, but I didn't have enough testing under my fingernails to accomplish the third.

But maybe I do now.

I'm going to start by working on my sort functions – building on what I did with the isSorted script block. Here's my basic bubble sort:

$bubble01 = {

(LT)#

.SYNOPSIS

Does a bubble sort on a provided array.


.DESCRIPTION

Basic bubble sort, runs through the array (length) number of times.

.PARAMETER $sourceArray

The array to be sorted.

#(GT)

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


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

{

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

{

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

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

$sourceArray[$i+1] = $temp

}

}

}

return $sourceArray # if none fail, then true

}

To finish this stage of the project, I need two things:


  • Test cases.
  • A way to evaluate test cases.

No comments:

Post a Comment