#include <iostream>
#include <iomanip>
#include <windows.h>
using namespace std;
struct DATA_INFO
{
int nData;
int nIndex;
};
void PrintData(int *prgData, int nDataCount, int nCountPerLine)
{
for (int i = 0; i < nDataCount; ++i)
{
if (i % nCountPerLine == 0)
{
printf("\n");
}
printf("%3d ", prgData[i]);
}
printf("\n");
}
void SwapData(int *prgData, int nDataPos, DATA_INFO *prgDataInfo, int nInfoPos, int nDataCount)
{
if (prgDataInfo[nInfoPos].nIndex == nDataPos)
{
return;
}
int nTemp = prgData[nDataPos];
prgData[nDataPos] = prgData[prgDataInfo[nInfoPos].nIndex];
prgData[prgDataInfo[nInfoPos].nIndex] = nTemp;
nTemp = prgDataInfo[nInfoPos].nIndex;
for (int i = 0; i < nDataCount; ++i)
{
if (prgDataInfo[i].nIndex == nDataPos)
{
prgDataInfo[i].nIndex = nTemp;
break;
}
}
prgDataInfo[nInfoPos].nIndex = nDataPos;
}
void SortData(int *prgData, int nDataCount, int nCountPerLine)
{
DATA_INFO *prgDataInfo = new DATA_INFO[nDataCount], cDataInfoTemp;
// 拷贝数据到临时缓冲区
for (int i = 0; i < nDataCount; ++i)
{
prgDataInfo[i].nData = prgData[i];
prgDataInfo[i].nIndex = i;
}
// 排序(由小到大)
for (int i = 0; i < nDataCount - 1; ++i)
{
for (int j = 0; j < (nDataCount - i - 1); ++j)
{
if (prgDataInfo[j].nData > prgDataInfo[j + 1].nData)
{
cDataInfoTemp = prgDataInfo[j];
prgDataInfo[j] = prgDataInfo[j + 1];
prgDataInfo[j + 1] = cDataInfoTemp;
}
}
}
// 最小,左上
SwapData(prgData, 0, prgDataInfo, 0, nDataCount);
// 次小,右上
SwapData(prgData, nCountPerLine - 1, prgDataInfo, 1, nDataCount);
// 第三小,左下
SwapData(prgData, nDataCount - nCountPerLine, prgDataInfo, 2, nDataCount);
// 第四小,右下
SwapData(prgData, nDataCount - 1, prgDataInfo, 3, nDataCount);
// 最大,中间
SwapData(prgData, nDataCount / 2, prgDataInfo, nDataCount - 1, nDataCount);
delete [] prgDataInfo;
prgDataInfo = NULL;
}
int main()
{
const int DATA_COUNT_PERLINE = 5;
const int DATA_COUNT = DATA_COUNT_PERLINE * DATA_COUNT_PERLINE;
int rgnData[DATA_COUNT] = {0};
// 随机生成25个小于1000的整数,方便调试
srand(GetTickCount());
for (int i = 0; i < DATA_COUNT; ++i)
{
rgnData[i] = rand() % 1000;
}
// 打印当前数组信息
PrintData(rgnData, DATA_COUNT, DATA_COUNT_PERLINE);
// 排序
SortData(rgnData, DATA_COUNT, DATA_COUNT_PERLINE);
// 打印排序后的数组信息
PrintData(rgnData, DATA_COUNT, DATA_COUNT_PERLINE);
system("PAUSE");
return 0;
}
追问复制进去是有错的
本回答被网友采纳