[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CInt » Art_Expressions_p1 » search » VI » BeginnersGuideToBasic » Editors » Linux » GUI » WhatLinksHere » CSharp » VBNET_ArraySort

Table of Contents

  • Introduction
  • The Built-In Sort
  • The Bubble Sort
  • How to sort an array of a structure
  • Where to go from here

Introduction

Everyone knows how to declare an array, but how do you sort them? How do sorts work? How do I sort an array of a structure?

The Built-In Sort

It is very easy to sort a one-dimensional array in VB.NET, there is a built in method that all arrays have that can sort. Let's say we have an array called MyArray. The code to sort it is:
MyArray.Sort(MyArray)


To sort descending, just use "MyArray.Reverse" after sorting it.

There are a few methods to sort an array without using built in features. The easiest one to understand is the bubble sort.

Bubble Sort

This is the idea of the bubble sort: Go through the list comparing every element to all those that come after it testing if they are bigger, if so then swap them. The reason that (in the code that follows) I made j start from 1 above i is that we have already tested all previous i's against it and decided the current i is the smallest of all the numbers preceding it and therefore to test against them again would be pointless. (I hope that made sense...).

For the example code that follows, let us say that the user sent in a string of numbers that were separated by " "'s Eg. "34 54 23 52 634 1 23". The first thing that we need to do is to use the built-in split method to return an array of numbers.

Now to the code:
Sub GetSortDisplay(Input as String)
 Dim Arr() as Integer 'Declare an array
 'Split based on " "
 Arr() = Input.Split(" ")
 'To sort - Bubble sort
 Dim i, j as integer
 for i = 0 to arr.count-2 'if there are 7 items then arr(6) is the upperbound
  for j = i + 1 to arr.count-1 'becuase we start from 0, an array with 7 items has 6 items. 
   'If the value at index i is smaller than the value at j (which is further on in the array) then swap them.
   'in order to make the biggest come first.
   if arr(i) < arr(j) then swap(arr(i),arr(j))
   'See below for swap. To do smallest to biggest then flip the "<"
  Next j
 Next i
End Sub
'This will swap a and b. We pass By Reference because we want to affect a and b.
Sub Swap(ByRef a, b as integer)
 Dim temp as integer
 temp = a
 a = b
 b = temp
End Sub 


How to sort an array of a structure

Let's say that you want to store Id, Name, Salary. They are not all the same type. Name is a string and Id as well as Salary is an integer. The way to store them is to make an array of a "Structure".

Lets say we have a structure:
 Structure Employee
   Dim Name As String
   Dim Id As Integer
   Dim Salary As Integer
 End Structure


And we created an array of them:
Dim Employees(10) As Employee


How do we sort them by id?

As we saw above (if not, I'm telling you now), most sorters work by using a compare method. The built-in sorter also works this way. By default, it uses a Comparer class that has one method - one that compares two elements in an array to one another and returns a value to tell the sorter which one is bigger. To get a little more technical, this comparer class implements the IComparer Interface. Well, lets not go by default... we can create our own class that implements the IComparer interface so that the sort method knows which element of our array should precede another. To do this, we have to override the Compare method of the IComparer interface. The compare function takes two objects as its parameters and returns an integer as its result. Let's say that X and y are the two parameters. Then: if X < Y then return a negative number if X = Y then return zero if X > Y then return a positive number So what we do is create a class that implements the IComparer interface and has a method that can compare two Employees and tell us which is bigger.

The code is something like this:
Class EmployeeComparer 
  Implements IComparer 'Implement the IComparer Interface 
  Overloads Function Compare (ByVal x As Object, ByVal y As Object) As Integer Implements IComparer.Compare
    Return CType(x, Employee).Id - CType(y, Employee).Id
    'If x.id is bigger than y.id then x.id-y.id will be positive. 
    'And if y.id is bigger, then x.id-y.id will be negative
    'And finally if they are equal then x.id-y.id will equal zero.
  End Function
End Class
Now with this class, the Sort procedure knows which Employee to give precedence (The one with the bigger ID). Now we can do the sort:
'First lets create a bunch of random employees
Dim i as Integer
Randomize
For i = 0 to 10 
 Employees(i).Id = Rnd()*100 + 1 'Generate a random number between 1 and 100 to test our comparer class
 Employees(i).Name = Chr(Asc("a") + i) 'Get the letters from a to k
Next i
'Now that we have generated some random Employees, lets show them
For i = 0 To 10
 MsgBox(Employees(i).Id & "  " & Employees(i).Name)
Next
'Create an instance of our comparer
Dim Comp as New EmployeeComparer
'Now lets use our interface to sort
Employees.Sort(Employees, Comp)
'Now lets show them again and see if they have been sorted
For i = 0 To 10
 MsgBox(Employees(i).Id & "  " & Employees(i).Name)
Next


Where to go from here

Look back at the compare method. You can make it even better. Let's say that x.id = y.id, why not sort it alphabetically now? It isn't hard to implement. All you need to do is say that if x.id - y.id = 0 then if x.name > y.name then return positive number, if it is smaller then return negative and if it is equal then return the one with a bigger salary. There, we just sorted them by all three. First by Id then by name then by salary. Note: The truth be told, Id's should be unique.... but the idea is there.

I hope this article was insightful,

Relman

last edited (August 19, 2006) by Hapa, Number of views: 40718, Current Rev: 3 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Site Management by Lars Hagelin at Kontantkort.se.