Monday, August 31, 2009

Sorting in C++

in C++ the library algorithm provides many easy to use algorithms. The sorting algorithm available is called sort. The contents of an array are sorted with

sort( array_name, array_name+array_size );

Sorting an integer array with sort:

#include <iostream>
#include <algorithm>

using namespace std;

void printArray( int array[], int size );

int main( void )
{
    const int SIZE = 8;
    int array[ SIZE ] = { 4, 6, 5, 7, 8, 1, 2, 3 };

    printArray( array, SIZE );
    sort( array, array+SIZE );
    printArray( array, SIZE );
}

void printArray( int array[], int size )
{
    int i = 0;

    while( i < size )
    {
        cout << array[ i ] << " ";
        ++i;
    }
    cout << endl;
}

The algorithm requires that the smaller than relation, <, has been defined for the elements of the array. To sort an array of structure, the < operator needs to be defined manually to the sorting function:

struct Student
{
    string name;
    int st_number;
};

bool compare( const Student& s1, const Student& s2 );
const int SIZE = 20;

int main()
{
    Student array[SIZE];
    // ...
    sort( array, array+SIZE, compare );
    // ...
}

bool compare( const Student& s1, const Student& s2 )
{
    if( s1.st_number < s2.st_number )
    {
    return true;
    }
    return false;
}

Reference: wikipedia, mathbits, daniweb

Previous post

Next post


No comments:

Post a Comment