Thursday, February 2, 2012

Selection Sort Implementation In C++

This is the code of the selection sort in C++

#include
using std::cout;

void swap(int * const, int * const);
void selection_sort(int [], const int);

int main()
{
    int A[] = {1, 2, 8, 74, 9, 0, -1, 7};
    selection_sort(A, 8);
    for(int i = 0; i < 8; i++)
        cout << A[i] << ' ';

}

void selection_sort(int A[], const int a_size)
{
    int index = 0;
    for(int i = 0; i < a_size; i++)
    {
        for(int j = i + 1; j < a_size; j++)
        {
            if(A[index] > A[j])
                swap(&A[index], &A[j]);
        }
        index++;
    }
}

void swap(int * const e1_ptr, int * e2_ptr)
{
    int temp = *e1_ptr;
    *e1_ptr = *e2_ptr;
    *e2_ptr = temp;
}

Please rate this topic.
If you have any question please comment.

No comments:

Post a Comment