e20-01.cpp

来自「游戏开发数据结构-Data.Structures.for.Game.Progra」· C++ 代码 · 共 90 行

CPP
90
字号
// =======================================================
//  Chapter 20, Example 1
//  The Bubblesort
// =======================================================
#include "Array.h"
#include "Sorts.h"
#include <iostream.h>
#include <stdlib.h>
#include <time.h>


// compare integers
int compareint( int l, int r )
{
    return l - r;
}


// compare the integers in reverse order
int compareintreverse( int l, int r )
{
    return r - l;
}


// compare floats
int comparefloat( float l, float r )
{
    if( l < r )
        return -1;
    if( l > r )
        return 1;
    return 0;
}



template<class DataType>
void PrintArray( Array<DataType>& p_array )
{
    int index;

    for( index = 0; index < p_array.Size(); index++ )
    {
        cout << p_array[index] << ", ";
    }
}


void main()
{
    Array<int> iarray( 16 );
    Array<float> farray( 16 );

    int index;

    // seed the randomizer, see Chapter 22.
    srand( time(0) );

    // fill up the arrays with random values
    for( index = 0; index < 16; index++ )
    {
        // 0-255
        iarray[index] = rand() % 256;

        // 0-1
        farray[index] = (float)(rand() % 256) / 256.0f;
    }


    BubbleSort( iarray, compareint );
    BubbleSort( farray, comparefloat );

    cout << "Integer Array: ";
    PrintArray( iarray );
    cout << endl;

    cout << "Float Array: ";
    PrintArray( farray );
    cout << endl;


    // reverse the integer array
    BubbleSort( iarray, compareintreverse );

    cout << "Integer Array Reversed: ";
    PrintArray( iarray );
    cout << endl;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?