Now we want to iterate over each item in our array, so we'll use array.foreach for that. This prevents any bugs from occurring from setting swap to true in the previous iteration and forgetting to reset it. The first thing we need to do in our do/block is reset the swap value. We can pass it as the condition into our while portion of our do/while loop. Since the condition we're going to test is whether or not a swap occurred in each iteration, we need to store a variable that holds that swap state for us. This is a perfect situation for a do/while loop in our algorithm. ![]() Since the way we know that an array is sorted is that no swaps occurred during it, we need to at least iterate over the array once in order to determine that it's sorted. We continue looping until we make a pass where no items have been swapped. ![]() Then if we've made a swap, we loop through the array again. If it is, we swap it in place, and we indicate that we've made a swap during this iteration. Each time we iterate over the array, we check if the current item is greater than the next item. Bubble sort works by looping over the array as many times as necessary to get it sorted. ![]() Instructor: To write the bubble sort algorithm, let's create a function that accepts an array, mutates that array for sorting and then returns that array.
0 Comments
Leave a Reply. |