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:

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>

No comments:

Post a Comment