2
var grossBrackets = new Array( '300', '400', '500', '600', '700', '800', '900', '1000' );   
function bracketSort( itemToSort ) {
        for( index = 0 ; index < grossBrackets.length ; index++ ) {
            if ( itemToSort < grossBrackets[index] ) {
                bracketData[index]++;
            } else if ( itemToSort > grossBrackets[7] ) {
                grossBrackets[7]++;
            }
        }
        return bracketData;
    }

This is my current code, and I basically want to sort the data into their proper brackets. My source code is really long, but when I input these numbers into the function:

200.18
200.27
200.36
200.45
200.54

bracketData prints 5,5,5,5,5,5,5,5 or is there a better way to do this?

Brackets: <300, <400, <500, <600, <700, <800, <900, <1000, greater than 1000

2
  • is bracketData a global variable, or should it be locally declared inside the function? Commented Apr 12, 2010 at 2:20
  • I left that part out, it's a global. Commented Apr 12, 2010 at 2:31

1 Answer 1

1

If you only want each item to be placed in one bracket, you need to end your loop over grossBrackets once you've found a match. You can do this with the break keyword, like so:

if ( itemToSort < grossBrackets[index] ) {
   bracketData[index]++;
   break;
} 

Incidentally, you're checking whether itemToSort is greater than grossBrackets[7] 8 times, one for each element in grossBrackets. You really only need to do this once, so it doesn't need to be in the loop.

Sign up to request clarification or add additional context in comments.

3 Comments

I understood everything except for the part where you said to take it out of the loop. How would you suggest to write it? Wouldn't I need to compare itemToSort with each element of the array to see which bracket it fits in?
Ahh, I see what you are saying. I got it :) Thanks!
Yeah, I'm sure it was confusing because I said "less" when I meant "greater". Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.