Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  HOME    TRACKER    Visual Basic

Bubble Sort Alphabetically

I thiought Option Compare Text would sort this Alphabetically, like a Dictionary? option Explicitoption Compare TextDim BubbleSort(1 to 10) as stringprivate Sub cmdAlphaBubbleSort_Click()Dim SortNumber as Integer, IndexNumber as IntegerDim TemporaryStorage as stringfor SortNumber = 1 to 10 for IndexNumber = 1 to 10 - SortNumber If BubbleSort(IndexNumber) > BubbleSort(IndexNumber + 1) then TemporaryStorage = BubbleSort(IndexNumber) BubbleSort(IndexNumber) = BubbleSort(IndexNumber + 1) BubbleSort(IndexNumber + 1) = TemporaryStorage End If next IndexNumber next SortNumber picShowSort.Cls for IndexNumber = 1 to 10 picShowSort.print BubbleSort(IndexNumber) next IndexNumberEnd Subprivate Sub Form_Load()BubbleSort(1) = "1200 North Michigan Avenue"BubbleSort(2) = "1200 West Lower Wacker Drive"BubbleSort(3) = "900 North Michigan Avenue"BubbleSort(4) = "899 South Michigan Avenue"BubbleSort(5) = "12 South Western Avenue"BubbleSort(6) = "100 East Ontario Street"BubbleSort(7) = "600 North Rush Street"BubbleSort(8) = "P.O. Box 1200"BubbleSort(9) = "P.O. Box 890"BubbleSort(10) = "100 West Ontario Street"End Sub

View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Bubble Sort, Quick Sort And Radix Sort
Greeting everyone,

Can anyone help me on writing a simple program on Bubble sort, Quick sort and radix sort in Visual C?

Need Bubble Sort To Read Two Seperate Text Files And Sort Data Into One List
I have two seperate text files, have to read the data from both, such as:

(file one)
2, Tom
5, Bill
3, Tony
7, Charlotte
1, Pedro

(file two)
6, Penelope
8, Joann
4, Mark
10, Jose
9, Gerald

Then open, read and sort the two files, then put that data into combined order (by the number) to come out as one list:

1, Pedro
2, Tom
3, Tony
4, Mark
5, Bill
6, Penelope
7, Charlotte
8, Joann
9, Gerald
10, Jose

My exposure so far with Bubble Sort has been comparing and sorting words that were entered into text boxes. That is the only code I have and does not match this current scenario. Need help with code on opening both files simultaneously and then bubble sorting. I know this needs to be an array.

Can someone tell me what to do or show a similar example I could follow? Thank you for any help.

Sort Alphabetically
I am trying to create a program that accepts 3 names and then display's these names in a picture box alphabetically. I cannot figure out how to sort the contents of a picture box.


How To Alphabetically Sort A Column.
Hey just need to sort a column in a sheet alphabetically right after they add something to the column.


Sort An Array Alphabetically
I have an array of strings that I want to sort alphabetically. Is there a function I can call to do that?

Sort Collection Alphabetically
does anyone have a quick sub that will sort a collection alphabetically?

for instance, if a collection holds objects of type User, which has FirstName and Surname properties, i was looking for something that would arrange the collection by User.Surname, and would be as simple as:

VB Code:
public sub SortCollection(byref col)   'does the sortend sub

?? is this possible ??

Alphabetically Sort Ini File
Is it possible to alphabetically or alphanumerically sort the Section Names in an ini file? Currently, if my understanding is correct, if you add a new Section Name it is appended to the end of the ini file. I want to populate an array of Command Buttons using the Section Names as the caption for the buttons and I would like to have them in alphabetical order if possible.


Sort A Listview But Not Alphabetically
Hello all,
I'm working with a listview. I need to sort the listview in this order. (These are names of data types and they are stored in one of the listview's columns)


As you can see, they are not alphabetical. There are approx. 20,000 to 30,000 items in the listview, so you can understand my need for an efficient algorithm.

I've considered using an enumeration, but apparently REAL is a keyword in VB.

Help greatly appreciated.


Sort A Txt File Alphabetically.
I'm somewhat familiar on how to do this with .Net (2003) with a bubble sort but I don't know what is involved on how to perform this task in VB6 so PLEASE beer with me. I have searched but came up with nothing.

I have a program that saves items to a small txt file that is like this for example:

I want to be able to sort alphabetically and save the file each time I add an item. It would look like this for example:

What is the appropriate way to open my example.txt file and sort it each time I add an item to the file.
Thank you.

Sort DataCombo Alphabetically
Hi all

I have a little aesthetic problem: i cannot sort alphabetically a recordset that is displayed in a datacombo.

I have two datacombos. First the user must select a value from the first (one recordset is used here) inside a datacombo_change event.
Then according to that keyword, there is another recordset that is made that is used to populate the second datacombo. This is the one i'm trying to sort. I tried using the SORT command after the

Code:Private Sub DataCombo1_Change()
    'Populate DataCombo2
    strSQL = "SELECT Name FROM Table1 WHERE Category = '" & DataCombo1.BoundText & "'"
    Set rsCombo2 = New ADODB.Recordset
    rsCombo2.Open strSQL, adoConn, adOpenForwardOnly
    rsCombo2.Sort = rsCombo2.Fields("Name").Name
    Set DataCombo2.RowSource = rsCombo2
    DataCombo2.ListField = rsCombo2.Fields("Name").Name
    DataCombo2.BoundColumn = rsCombo2.Fields("Name").Name
End Sub

I tried using: rsCombo2.sort
in various places but did not work. Does anyone know how to do this??
Thanx a lot xx


Edited by - stacey on 10/7/2002 5:06:52 AM

ADO - Sort DataCombo Alphabetically
Hi all

I have a little aesthetic problem: i cannot sort alphabetically a recordset that is displayed in a datacombo.

I have two datacombos. First the user must select a value from the first (one recordset is used here) inside a datacombo_change event.
Then according to that keyword, there is another recordset that is made that is used to populate the second datacombo. This is the one i'm trying to sort. I tried using the SORT command after the

Private Sub DataCombo1_Change()
'Populate DataCombo2
strSQL = "SELECT Name FROM Table1 WHERE Category = '" & DataCombo1.BoundText & "'"
Set rsCombo2 = New ADODB.Recordset
rsCombo2.Open strSQL, adoConn, adOpenForwardOnly
rsCombo2.Sort = rsCombo2.Fields("Name").Name
Set DataCombo2.RowSource = rsCombo2
DataCombo2.ListField = rsCombo2.Fields("Name").Name
DataCombo2.BoundColumn = rsCombo2.Fields("Name").Name
End Sub

I tried using: rsCombo2.sort
in various places but did not work. Does anyone know how to do this??
Thanx a lot xx


Quick Sort? Bubble Sort?
Hi! I have a form and some textboxes. I want to print form with a reporter I made myself.
The thing is I have to sort the Controls by TOP-LEFT, wich is the best way to do that?
Quick Sort? Bubble Sort?

Selection Sort && Bubble Sort ??
have selection sort and bubble sort same meaning? finding smallest numbers to largest numbers ?

Thank You!!

Sort Outputs In Textbox Alphabetically
I came to face such problem. I know this may seem easy, but haven't sleep for all night, brain kinda fly away...
Ok, what I need help on is if I am to have several inputs through a textbox, how do I sort the outputs containing all inputs in alphabetical order on another textbox?
1st input:
1st output:

2nd input:
2nd output:

3rd input:    
3rd output:    

Thank you for any kind help !!!

Edited by - joer_siv on 7/9/2004 5:58:45 AM

Sort ListBox Control Alphabetically
I would just like to know how I would sort the values in ListBox Control (in Excel) alphabetically? I know there is a method in Visual Basic to sort the values, but it does not seem to be the same with Excel VBA.

Thank you!!!

Sort Textbox Lines Alphabetically?
Is this possible with some instruction or do I have to make my own? Notice this is a RichTextBox.

Bubble Sort Help
Im having problems with the following code:

Dim n As Integer
Dim Found As Boolean
Dim Temp As Variant

Found = True

For n = 0 To (n - 1)

If numbers(n + 1) < numbers(n) Then
Temp = numbers(n)
numbers(n) = numbers(n + 1)
numbers(n + 1) = Temp
Found = False

End If
n = n - 1
Next n

Loop Until (Found = True) Or (n = 1)
End Sub

Numbers is an array of randomly generated numbers which i need to sort using the bubble sort algorithm, at the moment however it is not working.
Any help would be very much appreciated.

Need Help W/ Bubble Sort
I have a text file with 19 Names and ID numbers. How do I sort by the last name and if the last names are the same then I go by first name.

654321 Doe, John
123456 Doe, Jane
..Here is what I got.

Dim h, j, i As Integer
Dim strLastname(20) As String
Dim strFirstname(20) As String
Dim temp As String
For h = 1 To 19
For i = 1 To 20 - 1
If strLastname(i) > strLastname(i + 1) Then
temp = strGrades(i)
strLastname(i) = strLastname(i + 1)
strLastname(i + 1) = temp

Bubble Sort
'Do the following if recordnumber <= Latrecord in the file
Do While recordnumber <= LastRecord
Get #fileNumber, recordnumber, myrec
'Displays contents of file under appropriate headings
lblName.Caption = lblName.Caption & vbCrLf &
lblScore.Caption = lblScore.Caption & vbCrLf & vbCrLf & myrec.score
lblDate.Caption = lblDate.Caption & vbCrLf & myrec.Sdate
recordnumber = recordnumber + 1

the code above displays stuff from a file. i need a bubble sort thing that sorts the myrec.score so it shows the highest scores first in a list. ideas?

Bubble Sort
I am wanting to sort an array with bubble sort. THe array will be all numbers. I have a sorting routine, but when it sorts numbers like 10 and 12 and 1, it sorts like: 10,12,1 I want it to go in numrical order.

Thanks...heres my code
<pre><font color=blue>Public</font color=blue> <font color=blue>Sub</font color=blue> sort(tmparray)
<font color=blue>Dim</font color=blue> SortedArray <font color=blue>As</font color=blue> Boolean
<font color=blue>Dim</font color=blue> start, Finish <font color=blue>As</font color=blue> Integer
SortedArray = True
start = LBound(tmparray)
Finish = UBound(tmparray)

SortedArray = True

<font color=blue>For</font color=blue> loopcount = start <font color=blue>To</font color=blue> Finish - 1

<font color=blue>If</font color=blue> tmparray(loopcount) &gt; tmparray(loopcount + 1) Then
SortedArray = False
<font color=blue>Call</font color=blue> swap(tmparray, loopcount, loopcount + 1)
<font color=blue>End</font color=blue> If
<font color=blue>Next</font color=blue> loopcount
<font color=blue>Loop</font color=blue> Until SortedArray = True
<font color=blue>End</font color=blue> Sub

<font color=blue>Sub</font color=blue> swap(swparray, fpos, spos)
<font color=blue>Dim</font color=blue> temp <font color=blue>As</font color=blue> Variant
temp = swparray(fpos)
swparray(fpos) = swparray(spos)
swparray(spos) = temp
<font color=blue>End</font color=blue> Sub</pre>


Bubble Sort Help
Hello, i have a problem. I have an array of a user defined type. i need to arrange the array in order by two of the variables.

Type d_order
X As Integer
Y As Integer
End Type

Dim TempOrder(10) as d_order

each of the 10 TempOrder array's have an X and a Y variable, and i need to sort them in order in the array from 0 - 10 by these x/y variables. would i have to do 2 different bubble sorts for this? i'm not sure how to go about it, if somone could help me out it'd be a big help, thanks!

I Need Some Help With Some Bubble Sort...
Hello to everyone! Just sign in!

I need some help with the bubble sort, i have cheked the tutors bubble sort examples but did not get the solution 4 my case, here's the prob:

I'am making an contact book which have the ability (or so I would like it to have) to sort the information by name, address, or phone number... the problem goes to name, adress and all that use letters, since the sort
gives priority to uppercase letters

Solutions (theories in which I think that can be achieved):

1 - Make the txt boxs uppercase the first letter of any of its words
(john smith to John Smith).

2 - Use the my arrays to upperlevel all letters in all words and perform
the sort then lowercase them again (but i want them to maintain the
first letter in uppercase status).

Side questions:

1 - How can I focus a certain letter in a array string?
exp: the array "List(2, 4)" have the string "Paul", imagine that i want
to put a "9" in letter "u" - "pa9l". Or just retrieve the 4th character of
a special array or txt box.

2 - How in Gods name I delete a Picbox background? (maybe am just
stupid enough to realise how to do it).

3 - Is it possible to make the txtbox or any other VB tool to get a trans-
parent background so that i can add decent graphics in my program?

TKS ALOT 4 ur attention and sorry if any this info is in the tutors posts
since I don't have that much time search 4 the answer, i have to finish my project by the end of this mouth

Cheers everyone! And make games! (My next focus point)

Bubble Sort Help
My sort isn't working, when i debug it i see that its not going into the bolded IF statement. It reaches the IF statement but doesn't go into it and i'm not sure why. Also i'm pretty sure i'm not printing the records our correctly. (everythings is declared as global)

Private Sub BubbleSort()
ReDim myarray(100) As String
Start = Format$(Now, "hh:mm:ss")
SwapCount = 1
LastLoc = Counter
Do While SwapCount > 0
SwapCount = 0
LastLoc = LastLoc - 1
StartLoc = 1
NextLoc = 2
Do While StartLoc <= LastLoc
Compares = Compares + 1
[b]If Left(myarray(StartLoc), 4) > Left(myarray(NextLoc), 4) Then
temp = myarray(NextLoc)
myarray(NextLoc) = myarray(StartLoc)
myarray(StartLoc) = temp
DataMoves = DataMoves + 1
SwapCount = SwapCount + 1
End If[/b]
StartLoc = StartLoc + 1
NextLoc = NextLoc + 1
StartLoc = 1
Do while StartLoc <= 100 Then
IdNum1 = Left(myarray(StartLoc), 4)
CarName = Mid(myarray(StartLoc), 5, 20)
Print #4, vbTab & IdNum1 & vbTab & CarName
StartLoc = StartLoc + 1
If mainoutct3 > 49 Then
PageCount3 = PageCount3 + 1
mainoutct3 = 0
End If
End If
finish = Format$(Now, "hh:mm:ss")
totaltime = Finished(Start, finish)
End Sub

Need Bubble Sort Help
well, they say bubble sort is the easiest sort to learn but i just don't seem to get it, if someone knows where there is a well documented bubble sort example or some one could show me a ssmall documented example, that would be great.

i am new to vb and am trying to find basically, a line by line documented example of a bubble sort so i can get my head around it and move on to more complex matters.

any help anyone can give will be appreciated, thanks

Bubble Sort
Hi folks, me again.. annoying you

This time, i have a 1D array named totals(5) which is filled with user input. I have copied this to another array named sortedttls(5) And i want to perform a bubble sort on this.

I have 2 arrays, because i need to sort the second one, and if the first position on the second array = first position on first array, print winner on a label, and do this for all 5 positions, so that i have Winner, 2nd, 3rd, 4th, Last in 5 labels.

I will eventually get my bubble sort working, but how would i go about the second part of my problem? Would it just be a case of a lot of IF statements?


Help With Bubble Sort
I've just joined, i've looked at the faq's and looked at the sort page, but it's all too much for me. im a novice programmer, and i've gotta do this sort for my program at college. I've come up with the following code but every time i run it, i get subscript out of range, i msgboxed it to see where i was going wrong and it goes down from 7 to 1 then out of range.

Dim a As Integer
Dim c As Integer
Dim t As Integer
Dim size As Integer
size = 8

For a = 1 To size Step 1
MsgBox (a)
For c = size - 1 To c <= a Step -1
MsgBox (c)
If totalbr0(c - 1) > totalbr0(c) Then
t = totalbr0(c - 1)
totalbr0(c - 1) = totalbr0(c)
totalbr0(c) = t
End If
Next c
Next a

My array is totalbr0(1 to 8) as integer, i've got it so that it reads from a file and adds the sales column to the correct branch number (1 to 8). any help is appreciated. Thanks.

Bubble Sort Help!
hello i have been told to try and make a simple bubble sort, from an array/search that i have already created but it doesnt work can someone please help! the code i have at the moment is:

VB Code:
Dim varanimal(200) As StringDim numanimals As Integer Private Sub btnBubble_Click()Dim vartemp As StringDim x, y As IntegerDim varloops As Integervarloops = numanimals For x = 1 to varloops    If varanimal(x) > varanimal (x+1) Then       vartemp = varanimal (x)       varanimal (x) = varanimal(x+1)       varanimal (x+1) = vartemp    End IfNext xFor x= 1 to numanimals     lstSort.AddItem varanimal(numanimals)Next xEnd Sub

I am using VB6 and any help will be appreciated

Bubble Sort +??
I am stuck a gain. Seems to be getting a habit of mine.!!!
I have got my two forms and the codes running reasonably well now except for a few "minor" details
On the first form I still cannot stop getting multiple listings of the same directory name. Also how do I do the bubble sort using a variable arrived by counting the number of districts listed in the txtfile. I want of districts to load in alphabetical order.
On the second form I can get straight to the directory I requested in the inputBox by not closing that file and can then InputData into it. I need to use this file for both looking up the number and deleting a record but I'm stuck on as how to do this using dirname as this will vary depending on which directory was opened by the first form. The code works okay when I specify a directory name but that rather defeats the point.


VB Code:
Private Sub cmdAddName_Click()  Dim message As String, nom As String, phone As String  'Add a person's name and phone number  txtName.SetFocus  If (txtName.Text <> "") And (txtPhone.Text <> "") Then      'Open App.Path & "" & dirname & ".txt" For Append As #1      Write #1, txtName.Text, txtPhone.Text      txtName.Text = ""      txtPhone.Text = ""      txtName.SetFocus    Else      message = "You must enter a name and phone number."      MsgBox message, , "Information Incomplete"  End If  Close #1End Sub  Private Sub cmdPhone_Click()  Dim message As String  'Determine a person's phone number  If txtName.Text <> "" Then      If Dir(App.Path & "" & dirname & ".txt") <> "" Then          Call phoneNumber        Else          message = "Either no file has yet been created or "          message = message & "the file is not where expected."          MsgBox message, , "File Not Found"        MsgBox "You must enter a name.", , "Information Incomplete"   End If   End If  txtName.SetFocusEnd Sub Private Sub cmdDelete_Click()  Dim message As String  'Remove a person from the file  If txtName.Text <> "" Then      If Dir(App.Path & "" & dirname & ".txt") <> "" Then          Call DeletePerson        Else          message = "Either no file has yet been created or "          message = message & "the file is not where expected."          MsgBox message, , "File Not Found."      End If    Else      MsgBox "You must enter a name.", , "Information Incomplete"  End If  txtName.SetFocusEnd Sub Private Sub DeletePerson()  Dim nom As String, phone As Integer, foundFlag As Boolean  foundFlag = False  Open App.Path & "" & dirname & ".txt" For Input As #1  Open App.Path & "TEMP" For Output As #2  Do While Not EOF(1)    Input #1, nom, phone    If nom <> txtName.Text Then        Write #2, nom, phone      Else        foundFlag = True    End If  Loop  Close #1  Close #2  Kill App.Path & "New.TXT"  Name App.Path & "TEMP" As App.Path & "" & dirname & ".txt"  If Not foundFlag Then      MsgBox "The name was not found.", , ""    Else      txtName.Text = ""      txtPhone.Text = ""  End IfEnd Sub Private Sub phoneNumber()  Dim nom As String, phone As String  'Find the phone number for the name in txtName  txtPhone.Text = ""  Open App.Path & "" & dirname & ".txt" For Input As #1   nom = ""  Do While (nom <> txtName.Text) And (Not EOF(1))      Input #1, nom, phone  Loop  If nom = txtName.Text Then      txtPhone.Text = phone    Else      MsgBox "Person is not in file.", , ""      txtName.Text = ""  End If  Close #1End Sub  Private Sub CmdReturn_Click()'frmNames.Hide 'frmdistricts.ShowEnd Sub  FORM 2Dim message As String, dirname As String, tempdir As String    Private Sub cmdAddName_Click()  'Add a new directory name to file & create a new directory file with that name  dirname = InputBox("Enter directory name required or name of new directory")  If dirname <> "" Then      Open App.Path & "" & dirname & ".txt" For Append As #1    Else      MsgBox "You must enter a name.", , "Information Incomplete"  End If  'check for existing directory Open App.Path & "directory.txt" For Input As #2   Do While Not EOF(2)    Input #2, tempdir    Loop    Close #2     If tempdir <> dirname Then     'write new directory name     Open App.Path & "directory.txt" For Append As #3    Write #3, dirname    Close #3    End If  Call nameFormEnd SubPrivate Sub nameForm() ' move to next form  frmdistricts.Hide  frmNames.ShowEnd Sub Private Sub cmdview_Click()  Dim numdistricts As Integer  Open App.Path & "directory.TXT" For Input As #2  numdistricts = 0  Do While Not EOF(1)    Input #1, Value    numdistricts = numDisticts + 1    Loop    n = numdistricts  Close #2  Dim districts(1 To n) As String  '???how do I use a number that will vary depending on                                                                                     names in file                              Dim passNum As Integer, i As Integer, temp As String    For passNum = 1 To n        If districts(i) > districts(i + 1) Then            temp = district(i)            districts(i) = districts(i + 1)            districts(i + 1) = temp        End If    Next i    Next passNum    Do While Not EOF(2)        Input #2, dirname        LstDirs.AddItem dirname    LoopEnd Sub

Bubble Sort Help
Ok here's the problem. There are 104 records in the file it's reading right now. As you can see it's supposed to take any records over 100 and print them to Excess, right now it is taking record 101 and printing it 4 times. (Don't worry about the DuplicateRec because there isn't any in this file) Then in my Bubble sort the records are printing in assending order but its only printing 81 records, and the records that are missing are at the beginning, i think my counter is off somewhere but i'm not sure how to fix that. If someone sees anything wrong let me know.

VB Code:
Private Sub ClearArray()ReDim myarray(100) As String    For Counter = 1 To 100        IdNum = "****"        CarName = "********************"        QOH = "***"        Price = "*********"        QOO = "***"        Supplier = "*****"        myarray(Counter) = IdNum & CarName & QOH & Price & QOO & Supplier    NextEnd Sub  Private Sub BuildArray()ReDim Preserve myarray(Counter) As StringprevRec = "*************************"Counter = 0PageCount2 = 1Do Until EOF(1) Or Counter = 120 Or Left$(myarray(Counter), 5) = "*****"    Input #1, record    If record = prevRec Then        DuplicateRec    ElseIf Counter >= 100 Then        Excess    Else        Counter = Counter + 1        myarray(Counter) = record    End IfprevRec = recordLoopEnd Sub Private Sub Excess()Head2head3switch = TrueIf record = "" Then    Exit SubElse    IdNum1 = Left(myarray(Counter), 4)    CarName = Mid(myarray(Counter), 5, 20)    Print #2, vbTab & IdNum1 & vbTab & CarName & vbTab & vbTab & "Excess"    head3switch = True    mainoutct2 = mainoutct2 + 1    If mainoutct2 > 50 Then        head3switch = False        PageCount2 = PageCount2 + 1        Head2        head3switch = True        mainoutct2 = 0    End IfEnd IfEnd Sub Private Sub BubbleSort()ReDim Preserve myarray(100) As StringStart = Format$(Now, "hh:mm:ss")SwapCount = 1LastLoc = CounterPageCount3 = 1Head3Do While SwapCount > 0    SwapCount = 0    LastLoc = LastLoc - 1    StartLoc = 1    NextLoc = 2    Do While StartLoc <= LastLoc        Compares = Compares + 1        If Val(Left$(myarray(StartLoc), 4)) > Val(Left$(myarray(NextLoc), 4)) Then            temp = myarray(NextLoc)            myarray(NextLoc) = myarray(StartLoc)            myarray(StartLoc) = temp            DataMoves = DataMoves + 1            SwapCount = SwapCount + 1        End If    StartLoc = StartLoc + 1    NextLoc = NextLoc + 1    LoopLoopmainoutct3 = 1Do While StartLoc < 100    IdNum1 = Left(myarray(StartLoc), 4)    CarName = Mid(myarray(StartLoc), 5, 20)    Print #3, vbTab & IdNum1 & vbTab & CarName    StartLoc = StartLoc + 1    mainoutct3 = mainoutct3 + 1    If mainoutct3 > 50 Then        PageCount3 = PageCount3 + 1        Head3        mainoutct3 = 1    End IfLoop'to make a difference in the duration timeLongdur = 0Longdur1 = 0Do Until Longdur > 800000Longdur = Longdur + 1Do Until Longdur1 > 5000000Longdur1 = Longdur1 + 1LoopLoopfinish = Format$(Now, "hh:mm:ss")totaltime = Finished(Start, finish)Head4End Sub

Bubble Sort
Ah, the infamous bubble

I hold the copyright to that you know.... so if you use it, each time it iterates,legally, you owe me 5 cents...

Bubble Sort
i have the bubble sort going and it works question is how do you get the last element of an unknown array number to list in a textbox.

i did a listcount to get the total number in the array but i cant get it to put the number in the text box... i have

text1.text = myarray(listcount)

which displays the total number in my array not the number in the last array element

so i tried doing this:

y = myarray.listcount
text1.text = myarray(y)

but this gives me an error. what am i doing wrong?

Bubble Sort
What is the code for a bubble sort using input boxes to be used with an unkown amount of numbers to be inputed by the user?

I Need Bubble Sort
I cant use that quick sort I have to use bubble sort Its a requirmnet

Bubble Sort
I am having a problem with this bubble sort. It will only swap the first 2 items on my list & I want to sort them all


Dim nom(1 To 5) As String, Phone(1 To 5) As Single

Private Sub cmdDisplayStats_Click()
Call SortData
Call ShowData
End Sub

Private Sub Form_Load()
Dim i As Integer
Open App.Path & " est.TXT" For Input As #1
For i = 1 To 5
Input #1, nom(i), Phone(i)
Next i
Close #1
End Sub

Private Sub ShowData()
Dim i As Integer
'Display ordered table
For i = 1 To 5
picTable.Print nom(i); Phone(i)
Next i
End Sub

Private Sub SortData()
Dim passNum As Integer, index As Integer
'Bubble sort table in descending order by name
For passNum = 1 To 4
For index = 1 To 5 - passNum
If nom(index) < nom(index + 1) Then
Call SwapData(index)
End If
Next index
Next passNum
End Sub

Private Sub SwapData(index As Integer)
'Swap entries
Call Swapstr(nom(index), nom(index + 1))
Call SwapNum(Phone(index), Phone(index + 1))

End Sub

Private Sub SwapNum(a As Single, b As Single)
Dim temp As Single
'Interchange values of a and b
temp = a
a = b
b = temp
End Sub

Private Sub Swapstr(a As String, b As String)
Dim temp As String
'Interchange values of a and b
temp = a
a = b
b = temp
End Sub

Bubble Sort
Hi all,
I have been doing a lot of reading re: bubble sorts, but at times it is to complex to understand, can someone explain it to me please as simplified as they can.
Much appreciated
PS can anyone also give me an appropriate format re: pseudocode, e.g what works best for you.

Edited by - kiauk on 11/19/2003 4:24:03 AM

Bubble Sort 2d Array
Hi Guys

I'm trying to sort a tab delimited text file by reading it into an array, splitting it into a 2d array, doing a bubble sort on one column and returning the whole thing sorted.

It mostly works but the output is not exactly what I want. I'm pretty sure my code is ok but I may be missing something very obvious. Hopefully, one of you guys can spot it straight away...

Private Sub Command1_Click()
Dim line As String, intfilelen As Long, tmp As String
Dim r As Long, c As Long, rowArray() As String, colArray() As String, myArray() As String
Open App.Path & " est.txt" For Input As #1

Do While Not EOF(1)
Input #1, line

intfilelen = intfilelen + 1


Close #1

ReDim myArray(intfilelen, 7) As String
ReDim rowArray(intfilelen)

Open App.Path & " est.txt" For Input As #1

Open App.Path & "output.txt" For Output As #2

For r = 0 To intfilelen - 1
Input #1, line
rowArray(r) = line
For c = 0 To 7
colArray() = Split(rowArray(r), Chr$(9))

myArray(r, c) = colArray(c)


Close #1

'now need to sort myarray by column (c) 5

For r = 0 To intfilelen - 1
For c = 0 To intfilelen - 1
If myArray(c + 1, 5) <> myArray(c, 5) Then
tmp = rowArray(c)
rowArray(c) = rowArray(c + 1)
rowArray(c + 1) = tmp
End If

For r = 0 To intfilelen - 1
Print #2, rowArray(r)

Close #2

MsgBox "done"

End Sub

Any ideas what's wrong with it?!


Bubble Sort And Vailidation
Some of you have helped me get this project rolling and I appreciate all the help you have given. I have got the code together for taking a comma delimited file and performing calculations with it and putting it back together. I Need to check for validation of the fields before calculations. If the field is invalid then it needs to go to a log file that the user can call on. I also have to be able to automatically sort in alphabetical order and reverse alphabetical order by last name in a seperate sub or function.

example: John Doe, 1000, .09, 2000
anything else would be invalid including anything >1 in the 3rd field. Spaces in the wrong spot of the name.

Here is the code that I have. Could anyone help me out with this one?

Private Sub cmdCalculate_Click()
Dim strLines() As String
Dim strFields() As String
Dim x As Integer
Dim curbonus As Currency
Dim curTotalPay As Currency
Dim strFinalLine As String

'Check for empty fileName
If g_strFileSel = "" Then
MsgBox "Please select a .nbr file before clicking on of the sort buttons..."
Exit Sub
End If

Open g_strFileSel For Random As #1

Do Until EOF(1)
x = x + 1
ReDim Preserve strLines(x) As String
Line Input #1, strLines(x)

For x = LBound(strLines) To UBound(strLines)
If x = 0 Then
x = 1
End If

strFields = Split(strLines(x), ",")

'need to put validations here

curTotalPay = strFields(1) = (strFields(2) * strFields(3))
ReDim Preserve strFields(uBoound(strFields) + 1) As String
strFields(4) = curTotalPay
If strFields(4) > 5000 Then
ReDim Preserve strFields(UBound(strFields) + 1) As String
strFields(5) = "Promotion"
End If

strLines(x) = Join(strFields, ",") 'Puts the fields back in one array
TxtValidRecords.Text = ""

'Loop through all of the lines and display them
For x = LBound(strLines) To UBound(strLines)
TxtValidRecords.Text = TxtValidRecords.Text & strLines(x) & vbNewLine
Next x

Close #1

g_strFileSel = FrmCalculate.txtFileOpen

I forgot to mention that the IT guy said something about a shell function or something????

any and all help would be appreciated

Bubble Sort Error
ok can anyone see a problem with this bubble sort? or is there problems with bubble sort i'm not aware of?

For iOuter = 1 To 5 - 1
'Which comparison
For iInner = 1 To 4 - iOuter
'Compare this item to next item
If theArray(iInner).iAgeYears > theArray(iInner + 1).iAgeYears Then
cTemp = theArray(iInner)
theArray(iInner) = theArray(iInner + 1)
theArray(iInner + 1) = cTemp
End If
Next iInner
Next iOuter
The reason I ask is that the output is not always is the right order, it depends on the input, for example if the input is in exactly reverse order say


then the ouput gives


any ideas?

[VB6] Bubble Sort Problem
Dim A() As String
Private Sub Command1_Click()
Dim Textprima As String
Dim C As String
Dim Max As String

Text1.Text = Textprima
A = Split(Textprima, ",")

N = UBound(A)

For I = 2 To N
For J = N To 1 Step -1
If A(J - 1) > A(J) Then
C = A(J - 1)
A(J - 1) = A(J)
A(J) = C
End If
Next J
Next I

For cc = 2 To N
Text2.Text = A(cc)
Next cc

End Sub

I type my array in the Text1 box like: 1,4,2,3,5,7,6
Then I want to output this array ordered: 1,2,3,4,5,6,7 but it doesn't work..

What's the problem?

Simple Bubble Sort
Hey guys, im in kinda a stuck here. I knew how to bubble sort . but i forgot . haha, but this is what i have so far:

Private Sub Command1_Click()
Dim strData() As String, i As Integer, tempString As String
Text1.Text = "[1]A|[2]B|[1]C|[1]D|[2]E|[1]F"
strData() = Split(Text1.Text, "|")
For i = LBound(strData) To UBound(strData)
If i <> UBound(strData) Then
If Mid(strData(i), 1, 3) = "[2]" Then
tempString = strData(i)
strData(i) = strData(i + 1)
strData(i + 1) = tempString
End If
End If
Next i

For i = LBound(strData) To UBound(strData)
Debug.Print strData(i)
Next i
End Sub

but its not working correctly, as you will see when you run it. Can someone help? I want all [1]s first, then [2] last.

Time A Bubble Sort

What I need help on is how to time a bubble sort or a selection sort.
I already declared everthing, the only problem is the timer

Private Sub cmdbub_Click()
Timer1.Enabled = True
Do Until Sorted
Sorted = True
For num = 1 To 5000 - 1
If Rndnum(num) < Rndnum(num + 1) Then
temp = Rndnum(num)
Rndnum(num) = Rndnum(num + 1)
Rndnum(num + 1) = temp
Sorted = False
End If
Next num
For num1 = 1 To 5000
lstrnd1.AddItem Rndnum(num1)
Next num1
Timer1.Enabled = False
lbltime1.Caption = Timer

End Sub

The timer inteval is set to 500 and it so far it would output something like this
"65723.97" or somewhere close to that.
any help would be great

Bubble Sort's Have Me Stumped
I've tried using a bubble sort to arrange a list on number's user the sample i found on wikipedia

can someone please help me sort out my coding and explain the logic so i can follow and understand the process, any help will would be great as im still learning what im doing.

this is my coded attempt

VB Code:
Option ExplicitDim number(9) As IntegerDim hasswapped As BooleanDim temp As StringDim i As Integer Private Sub Form_Activate()mainEnd SubPublic Function main() 'numbersnumber(0) = "5"number(1) = "6"number(2) = "2"number(3) = "4"number(4) = "1"number(5) = "7"number(6) = "9"number(7) = "0"number(8) = "3"number(9) = "8"  'for loops and printing to screenFor i = 0 To 9 Print number(i)Next sort End Function Public Function sort() hasswapped = FalseFor i = 0 To 9 - 1    If number(i) > number(i) + 1 Then        temp = number(i) + 1        Print temp        hasswapped = True    End IfNextEnd Function


Help With Simple Bubble Sort
VB Code:
Private Sub cmd2_Click()     Dim moved As Boolean    Dim i As Integer    Dim tempStr As String    Do        moved = False        For i = 0 To List2.ListCount - 2             If List2.ItemData(i + 1) < List2.ItemData(i) Then                tempStr = List2.ItemData(i)                List2.ItemData(i) = List2.ItemData(i + 1)                List2.ItemData(i + 1) = tempStr                moved = True                End If            Next i        Loop Until moved = False  End Sub

to try and sort a list in to alphabetical order, but i have discovered that list.itemdata(index) doesnt actually return what i'ld expect.... so any clues?


Bubble Sort Array
Bubble Sort Algorithm

Array = array to be sorted
Number_of_elements = number of elements in the array
Elements_switched = flag to record if the elements have been switched in the current pass
Temp = temporary area for the holding an array element which is being switched
I = index for outer loop
J = index for inner loop

Set I to number_of_elements
Set elements_switched to true
DOWHILE ( elements_swiched and I >= 2
Set J to 1
Set elements_switched to false
DOWHILE J <= I – 1
IF array (J) > array ( J + 1) THEN
Temp = array(J)
Array (J) = Array (J+1)
Array ( J + 1) = temp
Elements_switched = true
J = J + 1
I = I -1

That’s it!, for Software Design and Development, I have to code that into visual basic, 200 items in the array, and output needs to be scrollable so that both the original array and sorted array can be viewed on the screen

but i dont have much of an idea wat do to, some i know is

First by declaring some values

Dim I to Integer
Dim J as Integer
Dim array(200) as Integer
Dim E_S as Boolean
Dim Temp as Integer
Dim max as Integer

Randomize ‘ randomizing the 200 numbers in the array

And then after this I sort of have no clue how to proceed. I know to get the array in the Scroll bar,

Something like

For x = 0 to 199
List1.list(x) = array(x)
Next x
But will that work for the sorted and unsorted?

but apart form that i have no idea, i understand the algorthim but no idea how to code it into vb code


Date Bubble Sort

I am trying to sort dates from numeric order to date order any help plaese



Count && Bubble Sort
Sorted out the bubble sort but now have added a new routine to count the entries in the textfile so now I want to use a variable in the bubble sort. I have tried using redim but something still does not work. I am slowly getting there as the bubble sort & the count both work alone. Just not together

VB Code:
Dim pnom() As String, Phone() As Single  Private Sub cmdView_Click()  Call talley  Call SortData  Call ShowDataEnd Sub Private Sub talley() Dim numEntries As Integer, nom As String  Open App.Path & "Test.TXT" For Input As #1  numEntries = 0  Do While Not EOF(1)    Input #1, nom    numEntries = numEntries + 1    n = numEntries  Loop  'picoutput.Print n  Close #1End Sub Private Sub Form_Load()  Dim i As Integer  Open App.Path & " est.TXT" For Input As #1  For i = 1 To n    Input #1, pnom(i), Phone(i)  Next i  Close #1End Sub Private Sub ShowData()  Dim i As Integer  For i = 1 To n    picoutput.Print pnom(i); Phone(i)  Next iEnd Sub Private Sub SortData()  Dim pnom() As String, Phone() As String  Dim passNum As Integer, i As Integer, temp As String  ReDim pnom(1 To n)  ReDim Phone(1 To n)   'Bubble sort Entries  For passNum = 1 To n - 1    For index = 1 To n - passNum      If dnom(index) > dnom(index + 1) Then          Call SwapData(index)      End If    Next index  Next passNumEnd Sub Private Sub SwapData(index As Integer)  'Swap entries  Call SwapStr(pnom(index), pnom(index + 1))  Call SwapNum(Phone(index), Phone(index + 1)) End Sub Private Sub SwapNum(a As Single, b As Single)  Dim temp As Single  'Interchange values of a and b  temp = a  a = b  b = tempEnd Sub Private Sub SwapStr(a As String, b As String)  Dim temp As String  'Interchange values of a and b  temp = a  a = b  b = tempEnd Sub

Bubble Sort/resolves
What am I doing wrong I am only getting 1 pass so only first to entries are sorted

VB Code:
Private Sub cmdDisplayStats_Click()  Call SortData  Call ShowDataEnd Sub Private Sub Form_Load()  Dim i As Integer  Open App.Path & " est.TXT" For Input As #1  For i = 1 To 5    Input #1, nom(i), Phone(i)  Next i  Close #1End Sub Private Sub ShowData()  Dim i As Integer  'Display ordered table  picTable.Cls  For i = 1 To 5    picTable.Print nom(i); Phone(i)  Next iEnd Sub Private Sub SortData()  Dim passNum As Integer, index As Integer  'Bubble sort table in descending order by name  For passNum = 1 To 4    For index = 1 To 5 - passNum      If nom(index) < nom(index + 1) Then          Call SwapData(index)      End If    Next index  Next passNumEnd Sub Private Sub SwapData(index As Integer)  'Swap entries  Call Swapstr(nom(index), nom(index + 1))  Call SwapNum(Phone(index), Phone(index + 1)) End Sub Private Sub SwapNum(a As Single, b As Single)  Dim temp As Single  'Interchange values of a and b  temp = a  a = b  b = tempEnd Sub Private Sub Swapstr(a As String, b As String)  Dim temp As String  'Interchange values of a and b  temp = a  a = b  b = tempEnd Sub

Tips And Bubble Sort....
(Hi Aaron! Are you? From Codeguru?! Have a nice day!!)

Tried to submit a tip to correct a common mistake you can find here:
but page of submitting have some matters. Tried a way to comunicate, but find none. Thus I post the tip here.
(Yes, this is not a question. Is a tip!)

Option Explicit

Private Sub Command1_Click()
''This code is twice faster than usual code
''you find under BubbleSort title
''(included code in this site....)
''This because of a small mistake that propagate
''throughout the net. It may not seems obvious, at
''first glance, but you can test it.

''for testing purpouse, uncomment the
''commented code and add a richtextbox to a form
'Dim i As Long
'Dim j As Long
'Dim numbers(1000) As Integer
'Dim temp As Long
'RichTextBox1.Text = ""
'For i = 0 To UBound(numbers)
' numbers(i) = Rnd * 100 + 1

For i = 0 To UBound(numbers) - 1
''usually mistake is here:
''most authors set j= 1 to...
''instead of set j=i to...
For j = i To UBound(numbers)
''then they set this if using only j
''and test for > of j+1
If numbers(i) > numbers(j) Then
temp = numbers(j)
numbers(j) = numbers(i)
numbers(i) = temp
End If
'For i = 0 To UBound(numbers)
' RichTextBox1.Text = RichTextBox1.Text & " " & numbers(i)
End Sub
'See you,
'Cesare Imperiali

Bubble Sort A Recordset ??
I have some data that I am showing in a grid. one of the Fields of the grid is Month which has data consisting of the first three letters of the month of that

S001 Tim Parker Jan
S002 Jim Marker Mar


Now I whenevr I click the head of any column on the grid, it sorts the grid accordingly.Now in the case of month, it sorts it Alphabetically, whereas I want the sorting to be chronological ( jan feb mar apr...).

How do I do this ??

I earlier thought of creating an enum type month with jan feb mar etc.. as the elements and then sort it using Bubble Sort or something. But now how do I bubble sort a recordset ? Or do I have to transfer it into a multidimensional array first ? efficient ?
possible ??

Copyright © 2005-08, All rights reserved