您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 市场营销 > 随机生成20个整数-快速排序-折半查找搜索给定元素
#includestdio.h#includestdlib.h#includetime.hintPartition(inta[],intlow,inthigh){//swapa[low]anda[high],returnthepivot'spositioninttemp=0,pivotkey=a[low];while(lowhigh){while(lowhigh&&a[high]=pivotkey)--high;temp=a[high];a[high]=a[low];a[low]=temp;while(lowhigh&&a[low]=pivotkey)++low;temp=a[high];a[high]=a[low];a[low]=temp;}returnlow;}intQSort(inta[],intlow,inthigh){//quicksorta[low...high]intpivotloc;if(lowhigh){pivotloc=Partition(a,low,high);QSort(a,low,pivotloc-1);QSort(a,pivotloc+1,high);}elsereturn0;}intSearch_Bin(inta[],intlow,inthigh,intz){//BinarySearchthenumberequaltothenumberyouaresearchingfor,ifit'sfounded,returntheposition.Otherwise,return-1intmid;mid=(low+high)/2;while(low=high){if(z==a[mid])returnmid;if(z==a[low])returnlow;if(a[mid]z)returnSearch_Bin(a,low,mid-1,z);elsereturnSearch_Bin(a,mid+1,high,z);}return-1;}intmain(){inti,t,s,res,low,high;intb[20];intrandomize();printf(Twentyrandomnumbers:\n\n);for(i=0;i20;i++){b[i]=rand();printf(%d\n,b[i]);}printf(Pleaseinput0tosort:\n\n);scanf(%d,&t);if(t==0){printf(Sortednumbersare:\n\n);if(QSort(b,0,19)==0){for(i=0;i20;i++)printf(%d\n,b[i]);printf(Pleaseinputthenumberyouwanttosearchfor:\n\n);scanf(%d,&s);res=Search_Bin(b,0,19,s);if(res!=-1)printf(index=%d\n,res+1);//ifthenumberisfound,outputthenumber'spositioninthesortedarrayelseprintf(Notfound\n);//ifthenumberisn'tfound,outputNotfound}}return0;}
本文标题:随机生成20个整数-快速排序-折半查找搜索给定元素
链接地址:https://www.777doc.com/doc-5836771 .html