您的位置:首页 > 其它

几种常见的排序算法

2014-09-01 19:30 190 查看
//冒泡排序
void sort1(int *nSort,int nLength)
{
for(int i = 0;i < nLength;i++)
{
bool bEnter = false;
for(int j = 1;j < nLength;j++)
{
if(nSort[j] < nSort[j-1])
{
int nTemp = nSort[j];
nSort[j] = nSort[j-1];
nSort[j-1] = nTemp;
bEnter = true;
}
}
if(bEnter == false)
{
break;
}
}
}
//插入排序
void sort2(int *nSort,int nLength)
{
for(int i = 1;i < nLength;i++)
{
int nSign = i;
int nTemp = nSort[i];
for(int j = i-1;j>=0;j--)
{
if(nTemp < nSort[j])
{
nSort[j+1] = nSort[j];
nSign = j;
}
else
{
break;
}
}
nSort[nSign] = nTemp;
}
}
//选择排序
void sort3(int *nSort,int nLength)
{
for(int i = 0;i < nLength;i++)
{
int nMin = nSort[i];
int nSign = -1;
for(int j = i;j < nLength;j++)
{
if(nSort[j] < nMin)
{
nMin = nSort[j];
nSign = j;
}
}
if(nSign != -1)
{
int nTemp = nSort[nSign];
nSort[nSign] = nSort[i];
nSort[i] = nTemp;
}
}
}

//快速排序
void sort4(int *nSort,int nStart,int nEnd)
{
int nLowIndex = nStart;
int nHighIndex = nEnd;
int nKeyIndex = (nStart+nEnd)/2;
int nKey = nSort[nKeyIndex];
while (nLowIndex < nHighIndex)
{
while (nLowIndex < nHighIndex && nKey > nSort[nLowIndex])
{
nLowIndex++;
}
nSort[nKeyIndex] = nSort[nLowIndex];
nKeyIndex = nLowIndex;
while (nLowIndex < nHighIndex && nKey < nSort[nHighIndex])
{
nHighIndex--;
}
nSort[nKeyIndex] = nSort[nHighIndex];
nKeyIndex = nHighIndex;
}
nSort[nKeyIndex] = nKey;
if(nKeyIndex-1 > nStart)
{
sort4(nSort,nStart,nKeyIndex-1);
}
if(nEnd > nKeyIndex+1)
{
sort4(nSort,nKeyIndex+1,nEnd);
}
}

//堆排序
void adjust(int *nSort,int nLength,int nIndex);
void sort5(int *nSort,int nLength)
{
for(int i = (nLength-1)/2;i >= 0;i--)
{
adjust(nSort,nLength,i);
}
for(int i = nLength-1;i >1;i--)
{
int nTemp = nSort[i];
nSort[i] = nSort[0];
nSort[0] = nTemp;
adjust(nSort,i,0);
}
}

void adjust(int *nSort,int nLength,int nIndex)
{
bool bEnter = true;
while(nIndex < nLength-1 && bEnter == true)
{
bEnter = false;
if(nIndex*2+1 <= nLength-1)
{
if(nIndex*2+2 <= nLength-1)
{
if(nSort[nIndex*2+1] < nSort[nIndex*2+2])
{
if(nSort[nIndex*2+1] < nSort[nIndex])
{
int nTemp = nSort[nIndex];
nSort[nIndex] = nSort[nIndex*2+1];
nSort[nIndex*2+1] = nTemp;
nIndex = nIndex*2+1;
bEnter = true;
continue;
}
}
else
{
if(nSort[nIndex*2+2] < nSort[nIndex])
{
int nTemp = nSort[nIndex];
nSort[nIndex] = nSort[nIndex*2+2];
nSort[nIndex*2+2] = nTemp;
nIndex = nIndex*2+2;
bEnter = true;
continue;
}
}
}
else
{
if(nSort[nIndex*2+1] < nSort[nIndex])
{
int nTemp = nSort[nIndex];
nSort[nIndex] = nSort[nIndex*2+1];
nSort[nIndex*2+1] = nTemp;
nIndex = nIndex*2+1;
bEnter = true;
continue;
}
}
}
}
}


都是花了一下午时间自己手打的,也算是回忆了一下,有的还调试了好久

特此记录

//希尔排序
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: