Sorting- and search algorithms

I’m currently doing some work to prepare for my next exam in programming. The exam involves explaining and implementing algorithms, in particular sorting- and search algorithms. In this post I will present my two attempts of implementing one of each kind.

First we have a sorting algorithm. It is the traditional Bubble Sort. Well, I won’t present any advantages or disadvantages but most of the sorting algorithms are fairly inefficient on large amount of data. The best way, I guess, is to combine different methods to make a good algorithm.

In bubble sort you simply step through each index and for each index you step backwards from the end to the current. Each time you then compare the items in the indices and swap if so.

This is my implementation in C#:

public static void BubbleSort(int[] array)
{
    int temp;

    /* Step through all indices. */
    for (int i = 0; i < array.Length; i++)
    {
        /* Step through the indices backwards to index i. */
        for (int y = array.Length - 1; y > i; y--)
        {
            /* Swap items if item y is less than item i. */
            if (array[y] < array[i])
            {
                temp = array[y];

                array[y] = array[i];
                array[i] = temp;
            }
        }
    }
}

With some modifications you could make it usable on other kinds of data too. This could be done by passing an IEnumerable<T> instead of an array. An array is an IEnumerable which is inherited by IEnumerable<T>, a generic interface.

However, although this is C#, implementing this algorithm in other languages is easy. There are no language or platform specific stuff in my implementation.

Moving on to the search algorithm. I have implemented a recursive version of Binary Search.

Basically, it cleaves the the list of sorted numbers in half and checks in which part it has a chance of finding the number to be searched for. This is done repeatedly until it has found the value.

Here’s the implementation:

public static int BinarySearch(this int[] array, int value, int from, int to)
{
    if(from < to)
    {
        int mid = (to + from) / 2;

        if (array[mid] == value)
        {
            return mid;
        }
        if (array[mid] > value)
        {
            return BinarySearch(array, value, mid, to);
        }
        else if (array[mid] < value)
        {
             return BinarySearch(array, value, from, mid);
        }
    }
    return -1;
}

This implementation of the algorithm has some flaws, it will return the last occurence of a number if it finds any other than just one. 
But per definition this should be enough because ‘2’ is ‘2’ and nothing else. Doesn’t matter if it is sorted.

Updated: October 29th, 2009.

Mitt liv med aspergers syndrom

Jag är väldigt öppen när det gäller mig själv och mina egenheter. Jag vill uppmärksamma diagnosen Aspergers syndrom som jag har. Det är ett neuropsykiatriskt funktionshinder och även den mildaste formen av autism.

Aspergers syndrom är en diagnos som beskriver personer som bland annat har begränsad förmåga till att söka kontakt med andra människor, har specialintressen som tar upp en stor del av deras uppmärksamhet och tid, kan ha svårigheter med att förstå och använda språk samt lätt att hamna i tvångsmässiga rutiner.

Jag föreslår att ni läser mer här på Riksförbundet Attentions websida om ni vill veta mer.

I det här inlägget vill jag dela med mig av min historia och berätta om hur jag har utvecklats genom åren.

Från då till nu

Det började tidigt så som jag har uppfattat det som. Man märkte redan så tidigt som i förskolan (brukar vara i den åldern) att jag hade svårigheter att umgås med andra barn. Först fick jag diagnosen DAMP, det som idag nästan är det samma som ADHD. Kort och gott betyder det brist på uppmärksamhet. Detta kanske för att jag då hade ett hett temperament samt att jag var en aning hyperaktiv. Jag hängde nog inte heller med så mycket i skolan och så för att jag var i “min egen värld”. Trots detta med den lilla begränsade kontakten med omvärlden så var jag var glad för uppmärksamhet. Inte på ett sådant sätt så att jag ville ta den ifrån andra med vilje. Jag kunde inte förstå hur andra tyckte och tänkte. Det var helt enkelt så att jag bara inte kunde förstå.
Jag kunde babbla på om mina intressen och sånt som intresserade mig utan att skapa en dialog med andra personer. Ett väldigt vanligt drag hos personer med aspergers syndrom. Trots detta var jag också blyg. Speciellt bland folk som jag inte kände. Det tog dock inte så lång tid för mig att vänja mig och börja lita på personer när jag väl mött dem.

Skolåren och min utveckling

Detta har däremot lagt sig med åren. Jag blev lugnare på högstadiet.  Jag blev faktiskt också mer reserverad då jag fick reda på min diagnos.
Min mamma hade så klart vetat om det länge.  För mig var det svårt även om jag då inte förstod vad det innebar att ha diagnosen. Jag har från den gången klassat mig själv som speciell men inte låtit mig bli stoppad av det.
För att vara ärlig har jag emellanåt ignorerat den av rädsla och en viss skam. Det var inte lätt att i skolan att vara annorlunda. Något som jag förstod trots mitt då begränsade sociala sinne. Jag hatade också att använda ordet “handikapp” om mitt tillstånd samtidigt som jag önskade att var “normal”.

Också för att tillägga är att jag har gått i vanlig skola i hela mitt liv.
Det har påverkat en hel del och det mesta positivt. Jag antar att jag inte hade kommit så långt som jag kommit nu om jag gått i specialklass. 
Det var så sent som när jag började gymnasiet som jag började ge mig in i det sociala samspelet. Det är något som alla “normala” människor lär sig automatiskt under uppväxten och sedan bär i bakhuvudet men som är en börda för mig. Det är som om jag måste ligga ett steg före.
Detta görs omedvetet. Ifrån mitt perspektiv är det en väldigt krävande process har jag kommit underfund med. 
Det är en del av aspergers syndrom. Det händer idag att jag tycker att det är jobbigt i sociala situationer. Men jag ser dock inte det som något större hinder längre.

Under min uppväxt har jag också haft perioder med rädslor och tvångsrutiner.
Dessa har oftast orsakats av fobier eller okunnande. När man ser tillbaka på dessa nu så kan man skratta åt det och undra hur man egentligen hamnade i de onda cirklarna. Som tur så händer inte detta längre.

Att jag har kommit så långt i min sociala och mentala utveckling har jag de människor runt omkring mig att tacka för. Sedan är det inte minst så att jag måste berömma mig själv för att ha vågat ta steget och själv velat förbättra mig. Jag kunde lika väl ha varit mer autistisk idag än vad jag är nu om inte jag blivit “tvingad” och väl vågat.

Specialintressen m.m.

Med mig har jag också haft den där drivkraften som jag fått av mina intressen. Liksom många andra “aspergare” har jag specialintressen.
Dessa har varierat genom åren. Alltifrån tåg när jag var liten till det långlivade intresset för datorer och numera också programmering.
Inte ovanligt bland aspergare. Det var också därför som jag valde att studera Software Engineering på BTH. Dessutom är jag också intresserad av språk och kultur. Jag gillar att resa och se mig omkring, Idag tycker jag att det är väldigt kul att träffa folk.

Vi aspergare kännetecknas för just vår förmåga att sätta oss in i detaljer. Detta drivs till större delen av ens intressen. Det är både en fördel och nackdel i livet. Detta kompenseras i någon grad av att man kan ha problem med att se helheten på saker och ting. Vissa tolkar saker bokstavligen.
Detta inkluderar saker som ordspråk och annat abstrakt. Jag har själv aldrig haft några större problem med det. Men sättet jag lär mig saker på påverkas av de här faktorerna.

Slutligen…

Det här var lite om mig då.

Till sist skulle jag vilja tacka alla som varit med mig de här åren.
Min familj och mina vänner, en väldigt stor grupp!.
Alla resor och personer som jag har mött så här långt har lämnat ett stort avtryck. Jag vill också tacka många andra som jag inte längre har någon kontakt med. Ni är också inräknade.

Speciellt tack till min polare/ledsagare Tobbe som har följt mig de senaste 6 åren. Du betyder så mycket för mig. Också mycket tack till Jesper, tysklärarinnan Evas pojk, som är min mentor i programutvecklingens underbara värld och lika så även han vän och moraliskt stöd.

Tack allihopa.

 

Uppdaterad: 091018

President Barack Obama gets awarded the Nobel Peace Prize

Today (October 9th, 2009) it was announced that this years recipient of the Nobel Peace Prize will be the sitting President of the United States, Barack Obama. That was a big surprise to the world because he only has been president for less than a year. Many think that it is too early but I think it is never too early for someone that shows his devotion for social policy in the world’s richest but yet unfairest country in the world. He has shown that there is need for a change. Do not forget what he has done in the international diplomacy to strengthen it and the cooperation between people. But we have yet a lot to expect from him. But again he certainly deserves it even if it may be to soon. 

Congratulations to you Mr. President!

 

Committee’s words:

"for his extraordinary efforts to strengthen international diplomacy and cooperation between peoples"

Profile at NobelPrize.org:

A little tip: NTCore’s Homepage

It has been a while since I last wrote a blog post. Hopefully I will do it soon, but for now I want to inform you about a site that I visited today.

It’s NTCore’s Hompage by Daniel Pistelli.  A site that I think every developer that is interested in software and platform internals should visit. There you find articles, and even “free” software to use.

Check it out!

Random numbers in C++

Here’s how you create seemly random numbers i C++. This will generate a random number from 1 to 10.


#include &amp;amp;lt;ctime&amp;amp;gt; // For time()

using namespace std;

void main()
{
srand(time(0));  // Initialize random number generator.
r = (rand() % 10) + 1;
}

For you legacy compiler users without namespace-support.

#include "cstdlib";  // Legacy for for srand() and rand()

Changes to the System.IO namespace in .NET Framework 4.0 BCL

These are not really any news for some of us but Microsoft has made some improvements to the classes in System.IO-namespace in the Base Class Library of the up-coming .NET Framework 4.0. New method-overloads that are returning IEnumerable<T> has been added for performance and usability.

Here’s a list of the new overloads:

System.IO.File
  • public static IEnumerable<string>ReadLines(string path)
  • public static void WriteAllLines(string path, IEnumerable<string> contents)
  • public static void AppendAllLines(string path, IEnumerable<string> contents)
System.IO.Directory
  • public static Enumerable<string> EnumerateDirectories(string path)
  • public static IEnumerable<string> EnumerateFiles(string path)
  • public static IEnumerable<string> EnumerateFileSystemEntries(string path)
System.IO.DirectoryInfo
  • public IEnumerable<DirectoryInfo> EnumerateDirectories()
  • public IEnumerable<FileInfo> EnumerateFiles()
  • public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos()

 

Code Capers has written an excellent blog post about this. You find it here.

Cross platform development with MonoDevelop 2.2

The Mono Team has now announced the first beta release of the new version (2.2) of their development tool Mono Develop. As the main motive of the Mono Framework is to provide as cross platform open-source implementation of the Common Language Runtime (CLR), the same standard as .NET, this version of MonoDevelop also supports more platforms than previous versions. In this up-coming release MonoDevelop also supports Windows.  So now you can develop .NET applications with MonoDevelop on any platform you want. Windows, Linux or Mac OS X. No need to switch to another system just stick with the one you feel comfortable with.

MonoDevelop now has an integrated debugger support, improved refactoring tools, code templates and on the fly formatting. Via add-ins you can now create ASP.NET MVC and Silverlight applications directly in MonoDevelop.

With MonoDevelop you can develop applications that run on various platforms including Windows, Linux, Mac OS X and iPhone. You can build graphical user interfaces using Stetic, an open-source visual designer for the cross platform GTK library via GTK#

Good work all you contributors out there! :)

 

imageMonoDevelop on Windows 

imageMonoDevelop on Mac OS X 

Read more:

Stack and Heap

This short blog post is a short introduction to the stack and the heap. A friend told me that he did not understand the meaning of these and the best way of explaining it is writing it down. And in this way it also gets public. :)

The stack is the place where variables are pushed when they are declared. Each time a function is called a new stack is created to store the variables declared in it. The stack is a data structure which as the name says stores data and operates as last-in-first-out (LIFO). When initializing a primitive type such as int (an integer) the variable will be pushed on the stack and the memory will be allocated for it on the the heap, which just is a place dedicated for allocating memory. The variable is statically bound to its address. Talking about scopes, all variables are declared in a scope and when it ends the variables get popped from the stack. The memory gets deallocated in the same turn. At least when we are dealing with values.

Reference variables

Opposed to this is when you declare a reference variable, for instance a class or a pointer, which actually just get pushed on the stack with no data location bound to it. It is said to be a null-reference. To assign data to it you have to assign the address of an existing memory location on the heap. Typically with the help from other variables that contains an address. References and pointers may change and point to another object of the type that it belongs to. The memory allocated to a reference does not get deallocated at the same time as the variable is popped from the stack. The rest differ by language or platform.

In programming languages

Short about memory management on different platforms and programming languages:

  • In C and C++ there are functions that can allocate memory on the heap for you. That is when you need to use pointers to refer to this memory location. The location allocated must be explicitly deallocated when it is no longer used (i.e. no references) or else it will cause a memory leak.
  • Java and C# do not require the programmer to handle memory as in C/C++. Both the Java Runtime and the Common Language Runtime (CLR) provides a mechanism called a garbage collector which does it automatically.

That was a little about the connection between the different types of variables and how they work with the memory, i.e. the heap.

Windows 3.11 on a virtual machine

The idea of installing Windows 3.11 came from my friend who wanted to try out some old legacy operating systems. He initially wanted to install NextSTEP on a virtual machine. NextSTEP from which he had experience from back home where his father had it installed on one of his computers. Although when he searched the Internet for the files he came to think about Windows and asked me about the old versions. I then told him about the version 3.11, which was one of the early Windows-branded operating systems released. It is actually an operating environment, a GUI for MS-DOS, which is the real operating system.

However, my friend installed it and I wanted to try it too. That is when I got the idea of writing a little tutorial.

To successfully install Windows 3.11 you need to get MS-DOS 7.10 and of course you need Windows 3.11. The full list of required stuff comes hereunder.

I assume that you know quite a lot about computers, but if you are no super-geek you won’t have any problems following these instructions anyway.

Preparation

This is the full list of things that you need:

  • MS-DOS 7.10 (ISO-image) can be downloaded for free due to its licensing under the GNU-GPL. Just search for it and you’ll find it.
  • Windows 3.11 (ISO-image) is on the other hand copyrighted by law. Do not ask med where you can get it. You may also find it on the Internet if you search for it. (Size: approx 11 MB)
  • You need any virtualization software that supports Windows as guest-OS. Try for example Windows Virtual PC, Microsoft Virtual PC or VirtualBox (cross-platform). All are available fro free – I use Windows Virtual PC on Windows 7. (If you are planning to install Windows 3.11 on a physical machine you do not need this).

1. Preparing the VM

Skip this if you are installing it on a physical machine. Observe that these instructions are not for any specific software.

Create a virtual machine. If needed specify the OS the virtual machine is going to run. Then create a hard disk with approximately 40 MB of space. I recommend dynamic size if available, but fixed size may work fine. Set the dedicated RAM to 10 MB. That will probably do fine. You may change it later if you need to.

Now mount the DOS-image as a drive and start the virtual machine. The installation will then boot automatically.

2. Installing MS-DOS

Time to install MS-DOS!

Once you have booted the disk a menu will appear. Select the first alternative by pressing the key 1.

Windows 3.11 - Windows Virtual PC

The setup will launch. Notice that you may use the mouse.

Windows 3.11 - Windows Virtual PC (2)

The setup will ask if it is going to create a new partition for you. Click Yes.

After that it will ask you to reboot and again start the setup as you did before.

This time it will install MS-DOS on your computer. If it ask you if you want to write a new MBR (Master Boot Record) you click Yes. The installation will now start copying and installing the OS.

Reboot when install is complete.

Once finished you should dismount the image from the virtual drive!

MS-DOS will start.

Windows 3.11 - Windows Virtual PC (19)

MS-DOS booted.

Windows 3.11 - Windows Virtual PC (8)

3. Installing Windows 3.11

Mount the Windows 3.11 install-image and write “D:\setup” (without quotes) to install Windows.

Windows 3.11 - Windows Virtual PC (9)

The install menu will launch. Press Enter to install.

Follow the instructions on the screen. The options provided in the installation are many and it is better to allow most of them.

The setup will ask you if you want to install drivers (known as plugins). Install the ones that are necessary. If your not sure about what drivers you should just install all of them.

The real install will launch shortly after. I promise you this will be done in a minute (or 2)!

Windows 3.11 - Windows Virtual PC (14)

First you provide some (pointless, in our case) info such as your name. You can leave the Product Number blank if you do not have one. Press Continue.

Files will then be copied to your hard drive, your virtual one.

Windows 3.11 - Windows Virtual PC (16)

When prompted for network setup you should ignore the dialog by pressing Continue.

(I will probably write another tutorial for getting the network devices running.)

Windows 3.11 - Windows Virtual PC (17)

Restart your computer when setup is complete.

Windows 3.11 - Windows Virtual PC (20)

Your virtual machine will start and DOS is booting up. In DOS you then type “win” (again without quotes). Just like it was said in the previous screen. Windows 3.11 will now start.

Windows 3.11 - Windows Virtual PC (18)

Here you have it! Windows 3.11 successfully running on a virtual machine.

Remember that you will have to enter DOS and write “win” everytime you want to start Windows. There surely is some trick to autostart Windows without entering DOS. But I won’t get into it this time.

Typecasting and type conversions in C#

Typecasts, or type conversions, is the name of the functionality which allows objects to converted into another form, another type of object. The syntax for these is primarily inherited from C/C++.

There are two scenarios involving typecasts:

  1. When casting between different types in an inheritance hierarchy.
  2. When calling a conversion operator.

These come like the ones in C/C++ in two flavors: implicit and explicit.

Implicit conversions

…are automatic and are carried out without any special notation. These also guarantee that no data will be lost during the conversion.

double d = 2; //Gives 2.0

Explicit conversions

…are operations that need to be explicitly stated in code.

This is to make sure that you are aware of that the conversion is going give a unexpected result.

For instance you have double-to-int conversions where you will loose data. You have to state that you know that the decimal number will be rounded to the nearest integer.

double d = 2.3;
int i = (int)d; //Gives 2

As you see you use the standard C notation with parenthesis, ( <type> ) .

You have to expect that an exception may be thrown if a type cannot be casted, especially with casts from Object. If you use an IDE such as Visual Studio you will probably be warned for eventual typecasts that will be unsuccessful before compiling your code.

But in our code everything seems to be in order.

Define a conversion operator

When defining your own class you may want to define your own conversion operators. These are defined as static methods with their own special syntax. The keywords implicit, explicit and operator are used.

Conversion operators are commonly used by classes in the .NET Framework Base Class Library. The primitive types have their own conversion operators to allow them to be converted into one another. These are seen in the samples above when turning an int into a double and vice versa.

Lets have a look at the syntax for defining the conversion operators.

Both samples take an int and cast it into an object of type MyClass. MyClass is also in this case the name of the declaring type.

Implicit conversion operator

public static implicit operator MyClass(int value)
{
    return new MyClass(value);
}

Using it:


MyClass x = 24;

Explicit conversion operator

public static explicit operator MyClass(int value)
{
    return new MyClass(value);
}

Using it:


MyClass x = (MyClass)24;

The as keyword

In C# there is a special way to do silent typecasts between types in the class hierarchy of a reference object. This makes use of the as-keyword.

object x = "Foo";
string y = x as String;   //Will succeed

When trying to cast this object to a class that not is of the declared type or a base class of the type the result will be null.

Random z = x as Random;    //Will fail and result will be null

So if it fails it will be null and no exceptions will be thrown. This is certainly useful in some cases.

Conclusions

In this short blog post you have been told a little about type conversion. It is pretty much the essentials.

Next Page »



Robert Sundström

Tweets

  • Waiting for the VS 2010 Beta 2 to be released to public. Only a couple of hours left. But still not sure when. Is it local time? 1 month ago
  • Writing meaningless programs.. 1 month ago
  • I consider myself being a logical being, but my logic is flaud. 1 month ago
  • SvD: Facebook gör dig smart – men Twitter fördummar (http://bit.ly/14XGNr 2 months ago
  • 2 weeks have passed since I came to Karlskrona. I pretty much enjoy living here. College has started and so far little coursework. 2 months ago

Recent Comments

Steve on Windows 3.11 on a virtual…
catchmikey on Wakoopa
Hillary on First days in Delsbo
wilhol on PC or Mac?

Categories

Calendar

November 2009
M T W T F S S
« Oct    
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Blog Stats

  • 15,604 hits