您的位置:首页 > 其它

动态数组 选择排序 二分搜索技术

2010-09-20 21:19 357 查看
 

实验课程:算法分析与设计
实验名称:基于排序的二分搜索技术    
实验目标:
(1)理解分治法的基本思想。
(2)分析二分搜索算法的时间复杂度,加深对时间复杂的理解。
实验任务:
(1)产生实验数据,即可手动输入,又可随机产生。
(2)用C++语言编程实现一种排序算法,如:简单排序、插入排序、选择排序或其他排序方法。
(3)用C++语言编程实现二分搜索算法。
(4)记录二分搜索过程中比较的次数,验证二分搜索的时间复杂度O(logn)。
实验设备及环境
PC;Visual C++等编程环境。
实验主要步骤:
(1)     明确实验目标和具体任务;
(2)     理解实验所涉及的算法;
(3)     编写程序实现排序算法和二分搜索算法;
(4)   产生实验数据(随机)作为输入,运行排序算法,将排序后的结果作为输入来运行二分搜索算法,记录运行的结果(包括:是否找到和比较的次数)。
(5)     根据实验数据及其结果得出结论。

下面是本人的代码:

 

 

 

// 第三周实验.cpp : Defines the entry point for the console application.
/*使用动态生成一位数组实现手动或随机生成一个数组。在使用选择排序实现数组的排序。
输入用户需要输入的数字,再在数组中查找,如果找到,输出查找的次数,并且输出这个数字在排好序的数组中的位置。
*/
#include "stdafx.h"

#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
using namespace std;

int devide_search(int *count,int x,int n);

int main(int argc, char* argv[])
{
 int flag;
 int temp;
 int k;
 int x; 
 int num; //作为要搜索的数的变量
 int m;
 
 
 int *count=new int[x];

 cout<<"请随便输入一个数字:";
 cin>>x;

 cout<<"请选择输入数组的方式(0(手动),1(随机)):";
 cin>>flag;
 if(flag==0)
 {
  for(int a=0;a<x;a++)
   cin>>count[a];
 }
 else if(flag==1)
 {
  for(int i=0;i<x;i++)
  {
   count[i]=rand()%x;
  }
 }
 else
  cout<<"输入有误!"<<endl;

 cout<<"随机生成的数为: /n";

 for(int j=0;j<x;j++)
 {
  cout<<count[j]<<"/t";
  if(j%10==0&&j!=0)
  {
   cout<<endl;
  }
 }
 cout<<endl;

/////////////////////////////////////////////////////////
/*对数组进行选择排序           */
/////////////////////////////////////////////////////////
 for(int z=0;z<x-1;z++)
 {
  k=z;
  for(int j=z+1;j<x;j++)
  {
   if(count[j]<count[k])
    k=j;
  }
  if(k!=z)
  {
    m=count[z];
    count[z]=count[k];
    count[k]=m;
  }
 }

 /////////////////////////////////////////////////////
 for(int y=0;y<x;y++)
 {
  cout<<count[y]<<"/t";
  if(y%10==0&&y!=0)
  {
   cout<<endl;
  }
 }

 cout<<endl;
 /////////////////////////////////////////////////////
 /*使用二分搜索对数组进行搜索                       */
 /////////////////////////////////////////////////////
 cout<<"请输入一个数字:";
 cin>>num;
 cout<<endl;

 temp=devide_search(count,num,x);

 if(temp==-1)
 {
  cout<<"在数组中找不到你要找的数!";
 }
 else
  cout<<"你要查找的数字在数组中的第 "<<temp<<" 位"<<endl;

 cout<<endl;
 delete[] count;
 return 0;
}

int devide_search(int *count,int num,int x)
{
 int left=0;
 int right=x-1;
 int sum=0;
 while(left<=right)
 {
  int middle=(left+right)/2;
  if(num==count[middle])
  {
   sum++;
   cout<<"二分搜索过程中比较的次数为:"<<sum<<endl;
   return (middle+1);
  }
  else if(num>count[middle])
  {
   sum++;
   left=middle+1;
  }
  else
  {
   sum++;
   right=middle-1;
  }
 }
 return -1;
}

 



 

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