Results 1 to 3 of 3

Thread: Plz Help Writing Gnome sort VB .NET

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Junior Member
    Join Date
    Aug 2004
    Posts
    32

    Plz Help Writing Gnome sort VB .NET

    Hi there-
    I am trying to right a Gnome sort in VB.net and it is just not doing what I want it to do. Here is what I have so far:

    Dim num() As Integer = {1, 9, 3, 6, 7, 2}
    Dim temp As Integer
    Dim i As Integer = 0

    While (i < 5)
    If (i = 0) Then
    Debug.WriteLine(num(i))
    i = 1
    End If

    If (num(i - 1) <= num(i)) Then
    i = i + 1
    Debug.WriteLine(num(i))
    Else
    num(i - 1) = num(i)
    i -= 1
    'Debug.WriteLine(num(i))
    End If
    Debug.WriteLine(num(i))

    End While

    I am not sure if its working or not. I think the while loop works because it the debug output give 6 values. the problem is the first three digits outputted are three 3's. Please help. Thanks.

  2. #2
    Junior Member
    Join Date
    Aug 2004
    Posts
    32
    Alright so I was able to get the sort to work. The only thing that will not sort is the last number of my array. Any suggestions??? Here is the code. The output of the following code will give 1,3,6,7,9,2

    Dim num() As Integer = {1, 9, 3, 6, 7, 2}
    Dim temp As Integer
    Dim i As Integer = 0

    While (i < 5)
    If (i = 0) Then
    i = 1
    End If

    If (num(i - 1) <= num(i)) Then
    i = i + 1
    temp = num(i - 1)

    Else
    num(i - 1) = num(i)
    num(i) = temp
    i = i - 1

    End If

    End While

    For i = 0 To 5
    Debug.WriteLine(num(i))
    Next

  3. #3
    Forum Techie A_old's Avatar
    Join Date
    Jan 2000
    Location
    Atlanta
    Posts
    10,663
    First, you should be looping while i < n (length of the array), not 5, so you can handle any size array of numbers.

    Second, the first and second conditional can be merged (using an or) since the algorithm simply requires one to move forward a spot in the array so the same code, i = i + 1, will work; why do you set temp in the second conditional at all? It only needs to be set when your current number is not greater than the preceding number (in the else clause). This could be where your "last number" issue comes from.

Bookmarks

Posting Permissions

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