
/**////
//从键盘输入10个整数到数组B中,然后对其排序,并显示中间结果
/**////
#include<iostream>
#include<iomanip> //setw() using it
using namespace std;
void main()
...{
const int n=10;
int b[n],i,j;
cout<<"input 10 integers:"<<endl;
for(i=0;i<10;i++)
...{
cin>>b[i];
}
for(i=0;i<n-1;i++)//need ten times sorting
...{
int largeEleIdx=i;
for(j=i+1;j<n;j++)//begin compare from next integer 
...{
if(b[j]>b[largeEleIdx])
largeEleIdx=j;//change the index
}
int temp;
temp=b[i];
b[i]=b[largeEleIdx];
b[largeEleIdx]=temp;//change the place
cout<<"i= "<<i<<" :";
for(j=0;j<n;j++)
...{
cout<<setw(6)<<b[j];
}
cout<<endl;
}
cout<<"result :";
for(i=0;i<n;i++)
cout<<setw(6)<<b[i];
cout<<endl;

/**////
//折半查找
/**////
int low=0,high=n-1,mid,key,midVal,found=0;
cout<<"search-element=";
cin>>key;
while(low<=high)
...{
mid=(low+high)/2;
midVal=b[mid];
if(key==midVal)
...{
found=1;
break;
}
else
...{
if(key>midVal)
high=mid-1;
else
low=mid+1;
}
}
if(found)
cout<<"index= "<<mid<<endl;
else
cout<<"no such element!"<<endl;

}
本文介绍了一个简单的程序,该程序允许用户输入10个整数并将其存储在一个数组中。接着,程序使用选择排序算法对这些整数进行排序,并在每次排序迭代后输出当前的数组状态。最后,程序实现了折半查找功能,以帮助用户确定特定元素在已排序数组中的位置。
1052

被折叠的 条评论
为什么被折叠?



