• missing xbfish.com image

Category Archives: Programming

Insertion Sort in C#

Insertion sort is an algorithm of sorting an array whereby elements are compared against and inserted towards the left position.

The insertion sort (ascending to descending) code in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
 
class Program
{
    static void Main(string[] args)
    {
        int [] array =  new int [10] {100, 50, 20, 40, 10, 60, 80, 70, 90, 30};
        int array_size = 10;
 
        Console.WriteLine("The array before Insertion Sort is: ");
        for (int i = 0; i < array_size; i++){
            Console.WriteLine("array[" +i +"] = " +array[i]);
        }
 
        // Now we will use Insertion sort
        int temp, k;
        for (int i = 1; i < array_size; i++) {
            temp = array[i];
            k = i - 1;
            while (k >= 0 && array[k] > temp) {
                array[k + 1] = array[k];
                k--;
            }
            array[k + 1] = temp;
        }
 
        Console.WriteLine();
        Console.WriteLine("The array after Insertion Sort is: ");
        for (int i = 0; i < array_size; i++) {
            Console.WriteLine("array[" + i + "] = " + array[i]);
        } 
    }
}

Here is a dancing video that illustrates insertion sort:

Bubble Sort in C#

Bubble sort is an algorithm of sorting an array whereby larger elements will be push to the back of the array.

The bubble sort (ascending to descending) code in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
using System;
 
class Program
{
    static void Main(string[] args)
    {
        int [] array =  new int [10] {100, 50, 20, 40, 10, 60, 80, 70, 90, 30};
        int array_size = 10;
 
        Console.WriteLine("The array before Bubble Sort is: ");
        for (int i = 0; i < array_size; i++){
            Console.WriteLine("array[" +i +"] = " +array[i]);
        } 
 
        // Now we will use bubble sort
        int temp;
        for (int index = array_size - 2; index >= 0; index--) {
            for (int i = 0; i <= index; i++) {
                if (array[i] > array[i + 1]) {
                    temp = array[i];
                    array[i] = array[i + 1];
                    array[i + 1] = temp;
                }
            }
        }
 
        Console.WriteLine();
        Console.WriteLine("The array after Bubble Sort is: ");
        for (int i = 0; i < array_size; i++) {
            Console.WriteLine("array[" + i + "] = " + array[i]);
        } 
    }
}

Here is a dancing video illustrating bubble sort:

Selection Sort in C#

Selection sort is an algorithm of sorting an array where it loop from the start of the loop, and check through other elements to find the minimum value. After the end of the first iteration, the minimum value is swapped with the current element. The iteration then continues from the 2nd element and so on.

The selection sort (ascending to descending) code in C#:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
using System;
 
class Program
{
    static void Main(string[] args)
    {
        int array_size = 10;
        int [] array =  new int [10] {100, 50, 20, 40, 10, 60, 80, 70, 90, 30};
 
 
        Console.WriteLine("The array before Selection Sort is: ");
        for (int i = 0; i < array_size; i++){
            Console.WriteLine("array[" +i +"] = " +array[i]);
        }
 
        // Now we will use selection sort
        int tmp, min_key;
 
        for (int j = 0; j < array_size - 1; j++){
            min_key = j;
 
            for (int k = j + 1; k < array_size; k++){
                if (array[k] < array[min_key]){
                    min_key = k;
                }
            }
 
            tmp = array[min_key];
            array[min_key] = array[j];
            array[j] = tmp;
        }
 
        Console.WriteLine("The array after Selection Sort is: ");
        for (int i = 0; i < 10; i++) {
            Console.WriteLine("array[" +i +"] = " +array[i]);
        }
    }
}

To compliment the above code, here is a dancing video to illustrate selection sort:

Difference between Parameters & Arguments

Paramters:
A parameter represents a value that the procedure expects you to pass when you call it. You can also indicate that a parameter is optional, meaning the calling code does not have to pass a value for it.

Arguments:
An argument represents the value you pass to a procedure parameter when you call the procedure. The calling code supplies the arguments when it calls the procedure. Each argument corresponds to the parameter in the same position in the list.

Extracted from: http://msdn.microsoft.com/en-us/library/9kewt1b3%28v=vs.80%29.aspx

Compiling C programming source files using GCC

Suppose we have these 2 files:
hello.c
bye.c

To compile and link these 2 files in one step through GCC:

gcc -o program hello.c bye.c

The output object will be program. To run the program, enter the following in the command line:

./program

We use the ./ to specify that we are running this file residing at the current folder only.

To compile the 2 files and link it through multiple steps:

gcc -c hello.c
gcc -c bye.c
gcc -o hello.o bye.o

The -c flag tells the compiler to compile only and not call the linker.

Quick Sort vs Bubble Sort

Interesting video!

Get a single character from string in C programming

Well, this is easy if you are familiar with pointers.

Suppose that you have this code to get the input from stdin stream:

#include <stdio.h>
 
int main(void){
   char destination[20], *ptr, c;
 
   fgets(destination, 20, stdin);
 
   return 0;
}

Next, you want to output each character line by line:

1
2
3
4
5
6
7
ptr = destination; // Have the pointer point to the array destination 
 
while(*ptr != '\0' && *ptr != '\n'){
   c = *ptr;
   printf("%c \n", c);
   ptr++;
}

The output will be each single character being printed out line by line, inclusive of white-space character.

Now, lets see what we have done over here. At line 3 of the second code snippet, the condition is set to run if *ptr != \0 and \n. Why? This is because a string terminated with a \0 character. As you get the input from stdin stream, fgets included the \n (newline character) when you press Enter key on the stdin stream before appending the \0.

For line 4, we set *ptr to c, a char variable. As ptr is pointing to the address of the string, we de-reference it to get the value. Since variable c is only able to hold a single character and ptr is pointing to a single character, the de-referenced of ptr will be a single character from the string.

Last but not least, we increment ptr to point to the next character of the string.

I hope this is a clear explanation for you. Do leave a comment if you have any problem :)

Tail recursion in Ruby

Under direct recursion, there is 2 main recursion style: 1) Traditional recursion, 2) Tail recursion.

So what are all these?

Take a look at the following example coded in Ruby:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def recursion(num, power)
	if power == 1
		return num
	else
		return num * recursion(num, power - 1)
	end
end
 
def tail_recursion(num, power, result)
	if power == 0
		return result
	else
		return tail_recursion(num, power - 1, result * num)
	end
end
 
puts "Please enter the number follow by the power:"
 
result = 1
num = gets.to_i
power = gets.to_i
 
puts "Trad recursion: " +recursion(num, power).to_s
 
puts "Tail recursion: " +tail_recursion(num, power, result).to_s

For recursion(), it is not efficient as the base case is not the last to be execute. The program will navigate to and back through the stack to return the final value.

Example:

recursion(2, 3)
2 * recursion(2, 2)
2 * (2 * recursion(2, 1))
2 * (2 * 2)
2 * (4)
8

As for tail_recursion(), the result will be return when the program reach the base case.

Example:

tail_recursion(2, 3, 1)
tail_recursion(2, 2, 2)
tail_recursion(2, 1, 4)
tail_recursion(2, 0, 8)
8

Include header file in C programming

If you want to use standard header files in C, you will include it like the one shown below:

#include <stdio.h>
#include <stdlib.h>

Now lets say you have a self-written header file, called custom.h, you will include it like this:

#include "custom.h"

Stack and Heap in Programming

Stack
The section of memory that is allocated for automatic variables within functions.

Heap
An area of memory used for dynamic memory allocation.

In general, the stack is a place in the computer memory where all the variables that are declared and initialized before runtime are stored. The heap is the section of computer memory where all the variables created or initialized at runtime are stored.

missing xbfish.com image

Extract from:
http://www.maxi-pedia.com/what+is+heap+and+stack
http://wiki.answers.com/Q/What_is_difference_between_heap_memory_and_stack_memory