数据结构例题

区分函数中引用变量和指针的用法

1.定义整型a,b,分别输入他们的值,再交换之后输出。

输入:1 2          输出:a=2,b=1

错误1:输出为a=1,b=2,只是形参值改变

#include <stdio.h>
#include <stdlib.h>

void swap(int p,int q)
{
    int t;
    t=p;
    p=q;
    q=t;
}
int main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    swap(a,b);
    printf("a=%d,b=%d",a,b);
    return 0;
}

 错误2:输出为a=1,b=2,只是地址交换了,实参未改变

#include <stdio.h>
#include <stdlib.h>

void swap(int *p,int *q)
{
    int *t;
    t=p;
    p=q;
    q=t;
}

int main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    swap(a,b);
    printf("a=%d,b=%d\n",a,b);
    return 0;
}

 错误3:输出为a=2,b=2

#include <stdio.h>
#include <stdlib.h>

void swap(int *p,int *q)
{
    int *t;
    t=p;
    *p=*q;
    q=t;
}

int main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    swap(a,b);
    printf("a=%d,b=%d\n",a,b);
    return 0;
}

 正确1:直接对指针所指的值进行修改

#include <stdio.h>
#include <stdlib.h>

void swap(int *p,int *q)
{
    int t;
    t=*p;
    *p=*q;
    *q=t;
}

int main()
{
    int a,b;
    scanf("%d%d",&a,&b);
    swap(a,b);
    printf("a=%d,b=%d\n",a,b);
    return 0;
}

 正确2:引用变量必须用c++

#include<cstdio>
#include<iostream>
using namespace std;

void swap(int &p,int &q)
{
    int t;
    t=p;
    p=q;
    q=t;
}

int main()
{
    int a,b;
    cin>>a>>b;
    swap(a,b);
    count<<"a="<<a<<","<<"b="<<b<<endl;
    return 0;
}

 二分查找法(时间效率的问题)

举例:数组a中存放从小到大排好序的n个整数,查找给定值k在数组中下标;若查找失败,返回-1

//函数部分
int BitSearch(int a[],int n,int k)
{
    int low=0,high=n-1,mid,found=0;
    while((low<=high)&&(found==0))
    {
        mid=(low+high)/2;
        if(k>a[mid])
        low=mid+1;
        else if(k==a[mid])
        found=1;
        else 
        high=mid-1;
    }
    if(found==1)
    return (mid);
    else
    return(-1);
}

 若n=15,此方法最多找四次(树的结构),而若一个一个数据对比需要找15次,对比之下,二分查找法时间效率会快很多。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zero_019

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值