您的位置:首页 > 其它

算法联系之一冒泡排序

2017-02-13 14:41 357 查看
记录下算法基础课

一、冒泡排序

// suanfatest.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

void swap(int *pInSrc,int index_0,int index_1);
void showresult(int *pArr,int lenArr);
void Sort_MaoPao(int *pInSrc,int lenInSrc,int *pOutDst,int lenOutDst);

int _tmain(int argc, _TCHAR* argv[])
{

int tmparr[]={111,10,150,3,22,300,1};
Sort_MaoPao(tmparr,sizeof(tmparr)/sizeof(int),NULL,0);
return 0;
}

/************************************************************************/
/*冒泡排序

*/
/************************************************************************/
void Sort_MaoPao(int *pInSrc,int lenInSrc,int *pOutDst,int lenOutDst)
{
//ASSERT(pInSrc!=NULL);
//ASSERT(pOutDst!=NULL);
int flag=lenInSrc-0;//记录最后一次无需排序的位置
int k=0;
while (flag>1)//因为每次都从1开始检查
{
k=flag;
for (int i=1;i<k;i++)
{
if(pInSrc[i-1]>pInSrc[i])
{
swap(pInSrc,i-1,i);
flag=i;
}
}

}

showresult(pInSrc,lenInSrc);

}

void swap(int *pInSrc,int index_0,int index_1)
{
int tmp0=pInSrc[index_0];
int tmp1=pInSrc[index_1];

pInSrc[index_0]=tmp1;
pInSrc[index_1]=tmp0;
}

void showresult(int *pArr,int lenArr)
{
printf("\r\n");
for (int i=0;i<lenArr;i++)
{

printf("%d ",pArr[i]);
}

}


void Sort_MaoPao_1(int *pInSrc,int lenInSrc,int *pOutDst,int lenOutDst)
{
int i,k=0;
int n=lenInSrc;
for (i=0;i<n;i++)
{
for (k=1;k<n-i;k++)
{
if(pInSrc[k-1]>pInSrc[k])//重点是 k-1 k 之间的比较
swap(pInSrc,k-1,k);
}
}

showresult(pInSrc,lenInSrc);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: