unsigned

以后要是一事无成,还娶了个很龊的老婆,这些年的书都白读了啊!

导航

笔试材料收集(二)——用OPENGL搞个冒泡排序,原创-_-!

冒泡排序,简单的不行,就不解释了。长久没搞OpenGL了,就弄个试试吧。受维基百科的启发,也搞个图形化的输出结果,直观易懂。

#include <time.h>
#include <GL/glew.h>
#include <GL/freeglut.h>

float green = 0.0f;// Represent the color factors of green and blue, to distinguish different array member
const int arrSize = 20;
int arr[arrSize];
int i = 0; //i and j are the loop variables, I make them global
int j = 0;

void CreateRandomList(int* arr, int size)
{
srand((unsigned)time(NULL));
for (int i = 0; i < size; i ++)
{
arr[i] = rand() % 100;
}
}

void DisplayList(int* arr, int size)
{
for (int i = 0; i < size; i ++)
{
float x1 = (float)i * 2.0f / (float)size - 1.0f;
float x2 = ((float)i * 2.0f + 1.0f) / (float)size - 1.0f;
float y1 = (float)arr[i] * 0.01f;
float y2 = y1 - 0.05f;
glColor3f(1.0f, y1, y1);
glRectf(x1, y1, x2, y2);
}
}

void BubbleSort(int* arr, const int size)
{
bool flag = true;
int temp;
for (; i < size - 1; i ++)
{
flag = true;
for (; j < size - i - 1; j ++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
flag = false;
break;
}
}
if (j == size - i - 1)
{
j = 0;
}
if (!flag)
{
break;
}
}
}

void RenderScene()
{
glClear(GL_COLOR_BUFFER_BIT);
glLoadIdentity();
DisplayList(arr, arrSize);
glutSwapBuffers();
}

void ChangeSize(int w, int h)
{
glViewport(0, 0, (GLsizei)w, (GLsizei)h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
double aspecRatio = (double)w / (double)h;
glOrtho(-aspecRatio, aspecRatio, -1.0, 1.0, 0.0, 1.0);
glMatrixMode(GL_MODELVIEW);
}

void TimeFunc(int value)
{
BubbleSort(arr, arrSize);
glutPostRedisplay();
glutTimerFunc(200,TimeFunc,0);
}

void initList()
{
CreateRandomList(arr, arrSize);
}
int main(int argc, char* argv[])
{
initList();
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
glutInitWindowSize(800, 600);
glutCreateWindow("Bubble Sort Demo");
glutReshapeFunc(ChangeSize);
glutDisplayFunc(RenderScene);
glutTimerFunc(200,TimeFunc,0);
glutMainLoop();
return 0;
}

 

posted on 2011-10-04 14:02  unsigned  阅读(609)  评论(0编辑  收藏  举报