Tuesday, January 3, 2012

Testing your sorting code in C++

When you write a method for sorting you probably want to test it.
Usually for that purpose a array of random numbers is created, printed directly after creating it and after running the sorting method. If the array is sorted afterwords the method should work.

To create an array filled with random numbers in c++ you need a for loop and a randomizer.
But at first lets create the array:
const int length = 20;
int notsorted[length];
 
This creates an integer array with a length of 20 (from 0 to 19).
Then lets initialize the randomizer:
srand((unsigned)time(NULL)); 

And after that lets write the array full of random numbers:
for (int i = 0; i < length; i++) {
    notsorted[i] = random(100);
}
 
Now we have an array full of random numbers. Exactly what we wanted.
We just need an output method to print the array to the console.
void output(int *a, int size) {
    for (int i = 0; i < size; i++) {
        cout << a[i] << endl;
    }
}
 
For this code to work you have to import following headers:
#include <stdlib.h>
#include <iostream.h>
#include <time.h>




Monday, January 2, 2012

Output in c++

Since you may want to test your sorting code you need some sort of output. Usually using a terminal and plain text. In c++ this is very simple: import iostrem.h with
#include <iostream.h>

You can now print something to the console via
cout << output;
 
This works also for input:
cin >> input;
 
If you want to print a complete array to the console use a for loop:
The endl command starts a new line. 
for (int i = 0; i < size; i++) {
    cout << a[i] << endl;
}





Bubblesort in C++/C

The code for bubblesort in c++ is relativly straightforwar:
 
void bubblesort(int *A, int length) {
    for (int i = length; i > 0; i--) {
        for (int j = 0; j < i; j++) {
            if (A[j] > A[j + 1]) {
                int tmp = A[j];
                A[j] = A[j + 1];
                A[j + 1] = tmp;
            }
        }
    }
} 
 
Two for loops and a comparison between two elements of the loop and a swap. When you know how bubblesort works you can write it in very many languages even if you're not good at them.