Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

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


Sorting

Arranging the elements of any array (or some key fields in them) into an ascending or descending order is called sorting. Since sorting is a field of coputer science that has been studied a lot, there are dozens of sorting algorithms available. Different algorithms and their efficiency is usually covered on the course Utilization of Data Structures. Pseudocode for these algorithms can be found in the literature. Cormen, Leiserson, Rivest, Stein: Introduction to Algorithms for instance. An efficient function for sorting data can often be found in one of the libraries.

Reference: wikipedia, sorting-algorithm, smith


Previous post

Next post