算法联系之一冒泡排序

来源:互联网 发布:java异步日志 编辑:程序博客网 时间:2024/04/30 20:15

记录下算法基础课

一、冒泡排序

// 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);}


0 0