[ create a new paste ] login | about

Link: http://codepad.org/UUZqOqC9    [ raw code | output | fork | 1 comment ]

C++, pasted on Jun 8:
#include <iostream>

template <typename T>
void printArray(T * array, int size, const std::string& space)
{
    for (int i = 0; i != size; ++i)
    {
        if (i != size - 1)
            std::cout << array[i] << space;
        else
            std::cout << array[i];
    }

    std::cout << std::endl;
}

template <typename T>
void numberSort(T * array, int size)
{
    printArray(array, size, "-");

    for (int i = 1; i != size; ++i)
    {
        std::cout << std::endl << "Iteration: " << i << std::endl;

        T tmp = array[i];
        int j = i - 1;

        bool bDone = false;
        do
        {
            if ( array[j] > tmp )
            {
                array[j+1] = array[j];
                printArray(array, size, "-");
                j -= 1;

                if (j < 0)
                    bDone = true;
            }
            else
                bDone = true;
        }
        while (!bDone);

        array[j+1] = tmp;
        printArray(array, size, "-");
    }

    printArray(array, size, "-");
}

int main()
{
    int array[] = { 50, 10, 20, 1, 5 }; //Array to sort
    int size = sizeof(array)/sizeof(int);

    numberSort<int> (array, size);
}


Output:
50-10-20-1-5

Iteration: 1
50-50-20-1-5
10-50-20-1-5

Iteration: 2
10-50-50-1-5
10-20-50-1-5

Iteration: 3
10-20-50-50-5
10-20-20-50-5
10-10-20-50-5
1-10-20-50-5

Iteration: 4
1-10-20-50-50
1-10-20-20-50
1-10-10-20-50
1-5-10-20-50
1-5-10-20-50


Create a new paste based on this one


Comments:
posted by diptiparmar430@gmail.com on Nov 27
Diptiparmar430@gmail.com
reply