Starbeamrainbowlabs

Stardust
Blog


Archive

Mailing List Articles Atom Feed Comments Atom Feed Twitter

Tag Cloud

3d account algorithms announcement archives arduino artificial intelligence assembly async audio bash batch blog bookmarklet booting c sharp c++ challenge chrome os code codepen coding conundrums coding conundrums evolved command line compiling css dailyprogrammer debugging demystification distributed computing downtime embedded systems encryption es6 features event experiment external first impressions future game github github gist graphics hardware hardware meetup holiday html html5 html5 canvas interfaces internet io.js jabber javascript js bin labs learning library linux low level lua maintenance network networking node.js operating systems performance photos php pixelbot portable privacy programming problems project projects prolog protocol protocols pseudo 3d python reddit reference release releases resource review rust secrets security series list server software sorting source code control statistics svg technical terminal textures three thing game three.js tool tutorial tutorials twitter ubuntu university update updates upgrade version control visual web website windows windows 10 xmpp

Sorting Algorithms 3 / 5: Insertion Sort

Hello again!

This is the 3rd of 5 sorting algorithms that I will be implementing and posting about.

Today I have a reverse insertion sorter for you.

An (reverse) insertion sort takes number one from the end of the array, and shuffles it along to the right until it is in the right place. Then it picks the next number along and does the same, until the whole array is sorted.

/// <summary>
/// Performs an insertion sort in the array.
/// </summary>
/// <param name="array">A reference to the array to sort.</param>
static void insertion_sort(ref int[] array)
{
    for (int i = array.Length - 2; i >= 0; i--)
    {
        int shp = i;
        //                                                        |
        //make sure that we don't fall off the end of the array V
        while(shp < array.Length - 1 && array[shp] > array[shp + 1]) 
        {
            swap_places(ref array, shp, shp + 1);
            shp++;
        }

        Console.Write("i: {0} ", i);
        print_array(ref array);
    }
}

Here is some example output:

[ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 23 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 22 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 21 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 20 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 19 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 18 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 53, 1, 38, 47, 63, 68, 91, 93 ]
i: 17 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 14, 1, 38, 47, 53, 63, 68, 91, 93 ]
i: 16 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 67, 1, 14, 38, 47, 53, 63, 68, 91, 93 ]
i: 15 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 97, 1, 14, 38, 47, 53, 63, 67, 68, 91, 93 ]
i: 14 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 69, 1, 14, 38, 47, 53, 63, 67, 68, 91, 93, 97 ]
i: 13 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 96, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 93, 97 ]
i: 12 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 92, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 93, 96, 97 ]
i: 11 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 95, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 92, 93, 96, 97 ]
i: 10 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 41, 1, 14, 38, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 9 [ 17, 10, 83, 67, 8, 50, 46, 63, 2, 1, 14, 38, 41, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 8 [ 17, 10, 83, 67, 8, 50, 46, 63, 1, 2, 14, 38, 41, 47, 53, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 7 [ 17, 10, 83, 67, 8, 50, 46, 1, 2, 14, 38, 41, 47, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 6 [ 17, 10, 83, 67, 8, 50, 1, 2, 14, 38, 41, 46, 47, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 5 [ 17, 10, 83, 67, 8, 1, 2, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 4 [ 17, 10, 83, 67, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 3 [ 17, 10, 83, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 91, 92, 93, 95, 96, 97 ]
i: 2 [ 17, 10, 1, 2, 8, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]
i: 1 [ 17, 1, 2, 8, 10, 14, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]
i: 0 [ 1, 2, 8, 10, 14, 17, 38, 41, 46, 47, 50, 53, 63, 63, 67, 67, 68, 69, 83, 91, 92, 93, 95, 96, 97 ]

Full source code (pastebin)

Binary (MD5: 01b2d774c70ce46d8e0641da948bc25e, SHA1: 537ee665162887f629200d8839b108a3e4098d38)

Algorithms 2 / 5: Reverse Selection Sort

It has been a while since I have implemented a sorting algorithm - I should probably have implemented these a little bit earlier than I have done :)

Today I bring you the C sharp version of the selection sort I posted earlier. To mix it up a bit htough this implementation is in reverse.

  1. Find the largest number in the sequence
  2. If it is larger than the number at the end of the array, swap them
  3. Find the next largest number
  4. If it is larger than the next number along from the end of the array, swap them
  5. Repeat steps 3 and 4 until all the numbers have been sorted.

Here is the code:

/// <summary>
/// Performs a selection sort on an array of ints.
/// </summary>
/// <param name="array">The array to sort.</param>
static void selection_sort(ref int[] array)
{
    int limit = array.Length - 1;
    while(limit > 0)
    {
        //find the index with the maximum value
        int max_index = 0; //set the max to the first element in the array
        //don't search the first element in the array, we have already done that on the line above
        for(int i = limit - 1; i > 0; i--)
        {
            if(array[i] > array[max_index])
                max_index = i;
        }
        if(array[max_index] > array[limit])
        {
            //we have found an index with a high value than the current limit
            swap_places(ref array, max_index, limit);
        }

        limit--;
    }
}

Full Source Code (pastebin) Link to binary (MD5: ef5e0f15c9bc181d36b193160e3f8ad9 SHA1: ad49eb97675ca6ec9cc9dfebb63fbe03cfa27534)

Next up: Insertion sorting.

Sorting: Selection Sort

Since I seem to be doing quite a few sorting algorithsms in my lectures at the moment, it would appear that I will be doing a series of sorting algorithm posts.

Today I did not have all that much time, so I wrote this one in javascript. I present to you: The selection sort.

The selection sort is a sorting algorithm where the smallest number is found and swapped with the number at the beginning, then the next smallest is swaped with the one next to the smallest number, and so on until the whoel sequence has been sorted.

Wikipedia has a rather nice animated GIF that explains the selection sort well here.

My implementation could be made faster be doing it in reverse, but I didn't have time to reverse it at the time of writing this post (check the comments to see if I did it later).

function selectionsort(arr)
{
    var maxid = 0, temp;
    for(var nextid = 0; nextid < arr.length - 1; nextid++)
    {
        //find the next smallest number remaining
        maxid = nextid;
        for(var j = nextid; j < arr.length; j++)
        {
            /*
            Invert to |
            sort desc.V */
            if(arr[j] < arr[maxid])
                maxid = j;
        }
        //swap the next number into place
        arr[nextid] = arr.splice(maxid, 1, arr[nextid])[0];

        console.log("nextid:", nextid, "state:", arr);
    }

    return arr; //for chaining
}

Here is a minified version (146 chars including newlines):

function selectionsort(e){for(var t=0,n=0;n<e.length-1;n++){t=n
for(var l=n;l<e.length;l++)e[l]<e[t]&&(t=l)
e[n]=e.splice(t,1,e[n])[0]}return e}

This was minified with UglifyJS.

Sample Output:

original [ 75, 4, 32, 87, 69, 73, 10, 18, 48, 2, 48, 96, 75, 36, 26 ]
nextid: 0 state: [ 2, 4, 32, 87, 69, 73, 10, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 1 state: [ 2, 4, 32, 87, 69, 73, 10, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 2 state: [ 2, 4, 10, 87, 69, 73, 32, 18, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 3 state: [ 2, 4, 10, 18, 69, 73, 32, 87, 48, 75, 48, 96, 75, 36, 26 ]
nextid: 4 state: [ 2, 4, 10, 18, 26, 73, 32, 87, 48, 75, 48, 96, 75, 36, 69 ]
nextid: 5 state: [ 2, 4, 10, 18, 26, 32, 73, 87, 48, 75, 48, 96, 75, 36, 69 ]
nextid: 6 state: [ 2, 4, 10, 18, 26, 32, 36, 87, 48, 75, 48, 96, 75, 73, 69 ]
nextid: 7 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 87, 75, 48, 96, 75, 73, 69 ]
nextid: 8 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 75, 87, 96, 75, 73, 69 ]
nextid: 9 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 87, 96, 75, 73, 75 ]
nextid: 10 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 96, 75, 87, 75 ]
nextid: 11 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 96, 87, 75 ]
nextid: 12 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]
nextid: 13 state: [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]
result [ 2, 4, 10, 18, 26, 32, 36, 48, 48, 69, 73, 75, 75, 87, 96 ]

At some point I may port this to C♯.

(Probably) Coming Soon: (Binary) Insertion sort, Merge Sort, Quick Sort.

Reverse Bubble Sorting

We had our second algorithms lecture this week - this time is was on bubble sorting. Apparently we will be doing several sorting algorithms over the next few weeks, each with their own strengths and weaknesses.

Today I bring you an optimised bubble sort implementation in C♯! This will be the first C♯ code that I have posted on this blog.

Basically, the bubble sort algorithm iterates over an array of numbers repeatedly and swaps those that are in the wrong order, until there aren't any more numbers left to swap.

Here is the script:

static void DoBubbleSort(int[]arraytosort) {
    int endingpoint = 1,
        temp;
    bool issorted;

    int swaps = 0,
        iterations = 0,
        passes = 0; //debug

    do {
        issorted = true;

        for(int i = arraytosort.Length - 1; i >= endingpoint; i--)
        {
            iterations++; //debug
            //Console.WriteLine("i: " + i + " i-1: " + (i - 1));

            if (arraytosort[i - 1] > arraytosort[i])
            {
                swaps++; //debug
                //swap the numbers around
                temp = arraytosort[i - 1];
                arraytosort[i - 1] = arraytosort[i];
                arraytosort[i] = temp;

                issorted = false;
            }
        }

        Console.Write("pass: " + passes + " ");
        printarray(arraytosort); //debug
        Console.WriteLine();

        passes++; //debug

        endingpoint++;
    } while (!issorted);

    Console.WriteLine("Sorting Complete!");
    Console.WriteLine("Statistics\n----------");
    Console.WriteLine("Passes: " + passes + ", Iterations: " + iterations + " Swaps: " + swaps);
}

...and here is an example of what it outputs:

Original: [66, 51,  0,  5, 42, 92,  8,  8, 28,  8]
pass: 0 [ 0, 66, 51,  5,  8, 42, 92,  8,  8, 28]
pass: 1 [ 0,  5, 66, 51,  8,  8, 42, 92,  8, 28]
pass: 2 [ 0,  5,  8, 66, 51,  8,  8, 42, 92, 28]
pass: 3 [ 0,  5,  8,  8, 66, 51,  8, 28, 42, 92]
pass: 4 [ 0,  5,  8,  8,  8, 66, 51, 28, 42, 92]
pass: 5 [ 0,  5,  8,  8,  8, 28, 66, 51, 42, 92]
pass: 6 [ 0,  5,  8,  8,  8, 28, 42, 66, 51, 92]
pass: 7 [ 0,  5,  8,  8,  8, 28, 42, 51, 66, 92]
pass: 8 [ 0,  5,  8,  8,  8, 28, 42, 51, 66, 92]
Sorting Complete!
Statistics
----------
Passes: 9, Iterations: 45 Swaps: 24

The script keeps track of the furthest point in the array it reached on each pass and goes one less each time - this is because the smallest number will always get pushed into its proper place at the left hand side on each pass.

As for the reason the script iterates backwards, in Javascript it is recommended that you iterate backwards to avoid repeatedly referencing Array.length, since it has to count the contents of an array upon each refernce. This is probably not the case with C♯, but it is a habit of mine :)

It is important to note that even though the function doesn't return anything, it still sorts the array because arrays are passed by reference by default, just like in Javascript (aka Ecmascript).

There are quite a few debug statements in there. Remove then for actual use in your code.

A (64 bit) compiled version of the script is available:

reversebubblesort.exe

Hashes:

Algorithm Hash
CRC32 644f6c6a
MD5 93fba7a072954ee6f34fcf44913eadc7
SHA1 01a54b24c475ec2ff1bf159dc1224e10553f430d
SHA-256 d32d689e2785d738c54e43a9dc70c1d8f2de76383022a87aa4f408519a7941cb
SHA-384 df7c4ac441aabaa1f182ade7532885d8ee5518c26f17d72d7952dcfaa39552dda9ad219a37661591fea169fd6ed514bb
SHA-512 c993509901bb65cd893d1c8455c5ad8dc670632e5476aad899980348b45bc3435cfab3fe6d8fd80606cfea3608770c9900be51e09f6f1a8c9fd5fe28169fd81d

Remember to always verify the integrity of your downloaded files, especially the larger ones. If you would like another type of binary (e.g. 32 bit, ARM, etc.), please post a comment below and I will reply with a download link. The compiler used was csc.exe on a Windows 7 64 bit command line.

Questions and / or comments are welcome below.

Art by Mythdael