# Sort Array Error • ### Question

• Dim VALUES() AS INTEGER = new Integer(4){100,1,0,34,98)

For d As Integer = 0 To VALUES.Length - 1
Dim tempa As Integer = VALUES(d)

Dim tempc As Integer

For T As Integer = 0 To VALUES.Length - 1
Dim tempb As Integer = VALUES(T)

If tempa > tempb Then

tempc = tempb
tempb = tempa
tempa = tempc
VALUES(d) = tempc

Else
VALUES(d) = tempb

End If

Next
tempc = 0
Next

My code inserts the last element in the VALUES array so that the array is only filled with that element, in this case, the array would only be filled with 98. I have tried everything, but am not sure

Saturday, September 9, 2017 6:31 AM

### All replies

• My code inserts the last element in the VALUES array so that the array is only filled with that element, in this case, the array would only be filled with 98. I have tried everything, but am not sure

It appears that you are trying to implement a bubble sort.   That sort algorithm requires that the elements of the array be swapped (or not) at each comparison.   But you are swapping the temp variables, not the array elements.  See, for instance:
http://www.codeguru.com/vb/gen/vb_misc/algorithms/article.php/c14627/Sorting-Algorithms-In-VB.htm#page-2

Saturday, September 9, 2017 6:51 AM
• My code inserts the last element in the VALUES array so that the array is only filled with that element, in this case, the array would only be filled with 98.

See the logic here:

https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Bubble_sort#Visual_Basic

- Wayne

Saturday, September 9, 2017 6:56 AM
• Thank you so much that worked :). I had no idea this was bubble sort, I did it in Java but never in VB.
Saturday, September 9, 2017 7:15 AM
• Hi John98k,

Te following code is method about bubble sort, please refer to :

```Private Sub sortfun()
Dim number As Integer() = {89, 76, 45, 92, 67, 12, 99}
Dim flag As Boolean = True
Dim temp As Integer
Dim numLength As Integer = number.Length
'sorting an array
Dim i As Integer = 1
While (i <= (numLength - 1)) AndAlso flag
flag = False
For j As Integer = 0 To (numLength - 1) - 1
If number(j + 1) > number(j) Then
temp = number(j)
number(j) = number(j + 1)
number(j + 1) = temp
flag = True
End If
Next
i += 1
End While
'Sorted array
For Each num As Integer In number
Console.Write(vbTab & " {0}", num)
Next