Results 1 to 14 of 14

Thread: [RESOLVED] Bubble Sorting an Array?!?!

  1. #1

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Resolved [RESOLVED] Bubble Sorting an Array?!?!

    I am trying to sort my array in ascending&Descending order, BUT im having trouble because the code to enter numbers and the code to sort the array was given to me by my professor but i changed the code to enter numbers into the array, so i think that's what messing my code to sort arrays up because the codes aren't matching up....any help is appreciated
    Code:
    Option Strict On
    
    Public Class Form1
    
        Dim J As Integer = 0
        Dim MyArray As New List(Of Integer)
    
    
        Private Sub btnPutNumberIntoArray_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPutNumberIntoArray.Click
            Dim number As Integer
            Integer.TryParse(txtNumbers.Text, number)
            If number < 1 Then
                MessageBox.Show("Please enter a number greater then zero.")
            Else
                MyArray.Add(number)
                txtNumbers.Clear()
    
            End If
        End Sub
    
        Private Sub btnDisplayNumbersInArray_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayNumbersInArray.Click
            txtDisplayNumbers.Clear()
            txtDisplayNumbers.Focus()
    
            For J As Integer = 0 To MyArray.Count - 1
                txtDisplayNumbers.Text &= MyArray(J).ToString & Environment.NewLine
            Next
        End Sub
    Private Sub btnDisplayAscendingOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayAscendingOrder.Click
         
            Dim SwapFlag As Boolean
            Dim UpperSub As Integer
            Dim Temp As Integer
            UpperSub = 24
            SwapFlag = True
    
            While SwapFlag = True And UpperSub >= 1
                J = 0
                SwapFlag = False
                While J <= UpperSub - 1
                    If MyArray(J) > MyArray(J + 1) Then
                        Temp = MyArray(J)
                        MyArray(J) = MyArray(J + 1)
                        MyArray(J + 1) = Temp
                        SwapFlag = True
                    End If
                    J = J + 1
                End While
    
                UpperSub = UpperSub - 1
    
            End While
                txtDisplayNumbers.Text = txtDisplayNumbers.Text & CStr(MyArray(J)) & ControlChars.NewLine
    
        End Sub
    
        Private Sub btnDisplayDescendingOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayDescendingOrder.Click
    
            Dim SwapFlag As Boolean
            Dim UpperSub As Integer
            Dim Temp As Integer
            UpperSub = 24
            SwapFlag = True
    
            While SwapFlag = True And UpperSub <= 1
                J = 0
                SwapFlag = False
                While J >= UpperSub - 1
    
                    If MyArray(J) < MyArray(J + 1) Then
                        Temp = MyArray(J)
                        MyArray(J) = MyArray(J + 1)
                        MyArray(J + 1) = Temp
                        SwapFlag = True
                    End If
                    J = J + 1
                End While
                UpperSub = UpperSub - 1
                txtDisplayNumbers.Text = txtDisplayNumbers.Text & CStr(MyArray(J)) & ControlChars.NewLine
    
            End While
    
        End Sub

    At the red Highlight i get this error:
    "Index was out of range. Must be non-negative and less than the size of the collection.
    Parameter name: index"
    Last edited by rosleenXOXO; Dec 14th, 2011 at 10:38 PM.

  2. #2
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Bubble Sorting an Array?!?!

    Ho hum, if you don't add enough values in to the List (you're not actually sorting an array, you realise?) you'll get that error. If you add too many values to the List, the end of it won't be sorted.

    You've got a hard-coded number of elements that you're trying to sort. But you have a variable length data set that you're sorting. Not happy bed-fellows.

  3. #3

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    Quote Originally Posted by Evil_Giraffe View Post
    Ho hum, if you don't add enough values in to the List (you're not actually sorting an array, you realise?) you'll get that error. If you add too many values to the List, the end of it won't be sorted.

    You've got a hard-coded number of elements that you're trying to sort. But you have a variable length data set that you're sorting. Not happy bed-fellows.
    Ok im now really confused. What would be enough values if my array can hold 25 elements? so what should i do to fix this? :/

  4. #4
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Bubble Sorting an Array?!?!

    You're not using an array, you're using a List. You add a single value to the List each time you click the btnPutNumberIntoArray button (assuming the number is valid).

    The List contains as many elements as you have added. (Unlike an array, which contains as many elements as you size it with)

    Therefore, if you have only added 1 element, trying to retrieve the value at position 1 will result in an IndexOutOfRangeException (remember that indices are zero-based, so you only have a position 0)

    Add two elements and you have position 0 and 1.
    Add a third and you have position 0, 1 and 2.

    And so on.

    You're trying to retrieve up to position 24 it looks like from a brief code inspection (though I may be suffering from an off-by-one error there), so you need to add 25 values to the list before the code will not throw an IndexOutOfRangeException.

    However, if you add more than 25 elements, those additional elements will not be sorted because the code will not try and go beyond position 24 in the List.

  5. #5

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    ok so i changed my code to where it only sorts 5 elements and it works but is there any way i can sort the list so i dont have to worry about how many elements are to be sorted

  6. #6
    PowerPoster Evil_Giraffe's Avatar
    Join Date
    Aug 2002
    Location
    Suffolk, UK
    Posts
    2,555

    Re: Bubble Sorting an Array?!?!

    You already know how to do that. Look at your btnDisplayNumbersInArray_Click_1 sub. That iterates over the (variable) length of the list.

  7. #7

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    would it be MyArray.Count - 1 ?
    I tried this it but it still doesnt work :/
    Code:
      
     Private Sub btnDisplayAscendingOrder_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplayAscendingOrder.Click
            txtDisplayNumbers.Clear()
            txtDisplayNumbers.Focus()
            Dim SwapFlag As Boolean
            Dim UpperSub As Integer
            Dim Temp As Integer
            UpperSub = 4
            SwapFlag = True
    
            While SwapFlag = True And UpperSub >= 1
                J = 0
                SwapFlag = False
                While J <= UpperSub - 1
                    If MyArray.Count - 1 > MyArray.Count Then
                        Temp = MyArray(J)
                        MyArray(J) = MyArray(J + 1)
                        MyArray(J + 1) = Temp
                        SwapFlag = True
                    End If
                    J = J + 1
                End While
    
                UpperSub = UpperSub - 1
    
            End While
            For J As Integer = 0 To MyArray.Count - 1
                txtDisplayNumbers.Text &= MyArray(J).ToString & Environment.NewLine
            Next

  8. #8

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    Also,
    How would i make the array in descending order?
    i thought all i had to do was flip the ">" sign to the opposite direction from the ascending array code :/

  9. #9

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    NVM on the last question about descending arrays, i figured it out :P
    BUTTT i still need help with the previous question

  10. #10
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Bubble Sorting an Array?!?!

    Yeah, that won't work. It kind of looks like you are guessing at solutions rather than thinking them through. Write this down on paper:

    Array Slot Value
    0 11
    1 9
    2 13
    3 17
    4 6
    5 8

    Once you have that written down, you could add those values into your list (but don't bother, yet, the point is that you COULD add those values, so what you have on paper is what your list would look like if you DID add them in).

    How many items are there? That number would be MyArray.Count, and you should see that there are 6 elements with indeces 0-5.

    So, if you look at the line you underlined:

    If MyArray.Count - 1 > MyArray.Count Then

    What does this do? You have already determined that for the example, MyArray.Count = 6, so MyArray.Count -1 = 5. Since 6 is never less than 5, this If statement will ALWAYS be false. That's clearly not what you want to do. But what DO you want to do?

    Next, take a look at that demo, and consider what each line of your method will do.

    The first line is actually this (ignoring the two lines that clear things):
    Code:
    UpperSub = 4
    4??? Why set UpperSub to 4? Where did 4 come from? You mentioned earlier that you got this working for 5 items. Therefore the purpose for the 4 is suggested, since 4 would be the maximum index value in a 5 item list. If we look at the next line this is supported:
    Code:
    While SwapFlag = True And UpperSub >= 1
    Clearly, you are looping a certain number of times, and since we later see that UpperSub is being decremented as the last item in the loop, you are counting down from 4 to 1. But your list no longer has four items, it has 6 items. So, would it work if you simply replaced UpperSub = 4 with UpperSub = 6 in the original code? Probably (though I haven't really looked at it), but that would leave you with the same initial problem that EG pointed out: You are hardcoding in the number of elements. What you want is to have the UpperSub, which is your number of iterations, be based on the number of elements in the list. What is that number of elements? It is MyArray.Count. However, you want UpperSub to be not the actual number of elements, but the maximum index, which is MyArray.Count - 1. So set UpperSub = MyArray.Count - 1 in your initial code.

    Now you can step through each line in your loop doing the same thing on paper, and see whether or not you get the result you expect. Alternatively, you could set a breakpoint on the While statement, and step through each line of code examining the variables with each step to see whether they are what you expect them to be.
    My usual boring signature: Nothing

  11. #11

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    NVM i figured it out agian,
    thanks for all your help!!!!

  12. #12

    Thread Starter
    Member
    Join Date
    Nov 2011
    Posts
    41

    Re: Bubble Sorting an Array?!?!

    Quote Originally Posted by Shaggy Hiker View Post
    Yeah, that won't work. It kind of looks like you are guessing at solutions rather than thinking them through. Write this down on paper:

    Array Slot Value
    0 11
    1 9
    2 13
    3 17
    4 6
    5 8

    Once you have that written down, you could add those values into your list (but don't bother, yet, the point is that you COULD add those values, so what you have on paper is what your list would look like if you DID add them in).

    How many items are there? That number would be MyArray.Count, and you should see that there are 6 elements with indeces 0-5.

    So, if you look at the line you underlined:

    If MyArray.Count - 1 > MyArray.Count Then

    What does this do? You have already determined that for the example, MyArray.Count = 6, so MyArray.Count -1 = 5. Since 6 is never less than 5, this If statement will ALWAYS be false. That's clearly not what you want to do. But what DO you want to do?

    Next, take a look at that demo, and consider what each line of your method will do.

    The first line is actually this (ignoring the two lines that clear things):
    Code:
    UpperSub = 4
    4??? Why set UpperSub to 4? Where did 4 come from? You mentioned earlier that you got this working for 5 items. Therefore the purpose for the 4 is suggested, since 4 would be the maximum index value in a 5 item list. If we look at the next line this is supported:
    Code:
    While SwapFlag = True And UpperSub >= 1
    Clearly, you are looping a certain number of times, and since we later see that UpperSub is being decremented as the last item in the loop, you are counting down from 4 to 1. But your list no longer has four items, it has 6 items. So, would it work if you simply replaced UpperSub = 4 with UpperSub = 6 in the original code? Probably (though I haven't really looked at it), but that would leave you with the same initial problem that EG pointed out: You are hardcoding in the number of elements. What you want is to have the UpperSub, which is your number of iterations, be based on the number of elements in the list. What is that number of elements? It is MyArray.Count. However, you want UpperSub to be not the actual number of elements, but the maximum index, which is MyArray.Count - 1. So set UpperSub = MyArray.Count - 1 in your initial code.

    Now you can step through each line in your loop doing the same thing on paper, and see whether or not you get the result you expect. Alternatively, you could set a breakpoint on the While statement, and step through each line of code examining the variables with each step to see whether they are what you expect them to be.
    Yeah, that won't work. It kind of looks like you are guessing at solutions rather than thinking them through.
    My professor is horrible, I've had to learn all this all by myself through the internet...
    so I am somewhat guessing to find the correct answer. You have been really helpful these couple past days with your responses and i am very grateful. You're probably saving my ass.

  13. #13
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Bubble Sorting an Array?!?!

    Quote Originally Posted by rosleenXOXO View Post
    My professor is horrible, I've had to learn all this all by myself through the internet...
    That is regrettably common.
    My usual boring signature: Nothing

  14. #14
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: [RESOLVED] Bubble Sorting an Array?!?!

    Let me also refer you to this site for sorting, which Evil_Giraffe told me about:

    All the common sorts are there. This one shows the bubble sort, but QuickSort is faster and better, and Shell sort is also of interest.

    http://www.youtube.com/watch?v=lyZQP...NSNbAHpPtlfRu3
    My usual boring signature: Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width