C++ 先对数组排序,在进行折半查找
2013-10-17 09:49
621 查看
第一步:输入15个整数
第二步:对这15个数进行排序
第三部:输入一个数,在后在排好序的数中进行折半查找,判断该数的位置
实现代码如下:
方法一:
选择排序法+循环折半查找法
#include<iostream>
using namespace std;
int main(){
int a[15];
int n,i;
void array_sort(int a[], int n);
int zeban(int a[], int start ,int end,int n);
cout<<"Please input 15 numbers:"<<endl;
for(i=0;i<15;i++){
cin>>a[i];
}
cout<<"Sorted order:"<<endl;
//==============选择排序========
array_sort(a,15);
//=======输出排序完成的数组====
for(i=0;i<15;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"please input a number:";
cin>>n;
//================折半查找==========
cout<<endl;
cout<<"number "<<n<<" locate in "<<zeban(a,0,14,n)<<endl;
return 0;
}
void array_sort(int a[],int n){
int i,j,k,tool;
for(i=0;i<n;i++){
k=i;
for(j=(i+1);j<n;j++){
if(a[j]<a[k]){
k=j;
}
}
tool=a[i];
a[i]=a[k];
a[k]=tool;
}
}
int zeban(int a[],int start,int end,int n){
int tag=-1;
for(start=0,end=14;start<=end;){
if(n==a[(start+end)/2]){
tag=(start+end)/2+1;
return tag;
}else if(n<a[(start+end)/2]){
end=(start+end)/2;
}else if(n>a[(start+end)/2]){
start=(start+end)/2;
}
}
}
第二种方法:
冒泡排序法+递归折半查找法
#include<iostream>
using namespace std;
int main(){
int a[15];
int n,i;
void array_sort(int a[], int n);
int IterBiSearch(int data[], const int x, int beg, int last);
cout<<"Please input 15 numbers:"<<endl;
for(i=0;i<15;i++){
cin>>a[i];
}
cout<<"Sorted order:"<<endl;
//==============选择排序========
array_sort(a,15);
//=======输出排序完成的数组====
for(i=0;i<15;i++){
cout<<a[i]<<" ";
}
cout<<endl;
cout<<"please input a number:";
cin>>n;
//================折半查找==========
cout<<endl;
cout<<"number "<<n<<" locate in "<<IterBiSearch(a,n, 0, 14)<<endl;
return 0;
}
void array_sort(int a[],int n){
int i,j,tool;
for(i=0;i<n;i++){
for(j=0;j<(n-i-1);j++){
if(a[j]>a[j+1]){
tool=a[j];
a[j]=a[j+1];
a[j+1]=tool;
}
}
}
}
int IterBiSearch(int data[], const int x, int beg, int last)
{
int mid = -1;
mid = (beg + last) / 2;
if (x == data[mid])
{
return (mid+1);
}
else if (x < data[mid])
{
return IterBiSearch(data, x, beg, mid - 1);
}
else if (x > data[mid])
{
return IterBiSearch(data, x, mid + 1, last);
}
return -1;
}
您可能感兴趣的文章:
相关文章推荐
- 先对数组排序,在进行折半查找(C++)
- 先对数组排序,在进行折半查找(C++)
- 先对数组排序,在进行折半查找(C++)
- sort函数的用法(C++排序库函数的调用) 对数组进行排序,在c++中有库函数帮我们实现,这们就不需要我们自己来编程进行排序了。 (一)为什么要用c++标准库里的排序函数 Sort()函数是c+
- 挑战30天C++入门极限-C/C++中利用数组名/指针进行排序实例
- C++中利用数组对字符进行除重和排序
- C++ 初学者指南 第四篇(4)对数组进行排序
- C++ 对数组进行排序并返还对应索引号
- C++利用指针数组和快排对输入的字符串进行排序
- C++中用冒泡排序算法对一个数组中的元素进行排序
- C++向数组内插入一个数并进行排序
- 按指定顺序进行数组排序 C++
- C++:多线程编程学习:利用多线程进行归并排序。
- C/C++复习:数组作实参,指针作形参排序
- 【php数组函数序列】之sort() - 对数组的元素值进行升序排序
- array_multisort 对关联数组进行排序的问题 PHP
- 利用函数指针对数组进行排序
- 给object数组进行排序(排序条件是每个元素对象的属性个数)
- python 统计数组中元素出现次数并进行排序的实例
- 运用选择法对数组中的数进行排序