c语言中的折半排序法是怎样的,基本程序是怎样的

c语言中的折半排序法是怎样的,基本程序是怎样的,第1张

折半法

应该叫做2分法。

用2分法查找数

需要先对数组进行排序(升序或降序)

假如你所要查找的数是20

数组是 1 4 7 8 20 30 34

每次都拿中间的数跟你要比的数比

也就是 8和20比

发现20比8大

所以左面伏正猜的数都不要了

剩下的是 20 30 34

再拿20跟30比

发现20比30小

右面的数都不要了

再拿20跟20比

相等,则找到了。

如果找不到返回-1

下面是程序。

#include <iostream>

using namespace std

int binarySearch(int* data,int low,int high,int value)

{

int k=(low+high)/2

if(value<*(data+low)||value>*(data+high))

{

return -1

}

if(value<*(data+k))

{

return binarySearch(data,low,k-1,value)

}

else if(value>*(data+k))

{

return binarySearch(data,k+1,high,value)

}

else

return k

}

void main()

{

int pos

int arr1[9]={1,2,3,4,5,6,7,8,9}

int i=9

while(i)

{

pos=binarySearch(arr1,0,8,i)

cout<<"数字"<<i<<"的下标清李是:"<<pos<<endl

i--

}

pos=binarySearch(arr1,0,8,20)

cout<<"数字20的下标是:"<<pos<<缺型endl

}

方法/步骤:程序实现: 写一个折半插茄友入排序法的函数名,包含参数。 int TwoSort(int * ListData,int ListLength)写一个循环,在循环中应颤缺槐用折半扮茄插入排序。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12296131.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存