欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++基础算法-冒泡排序,二分查表

程序员文章站 2022-03-15 21:57:36
...

二分查表

给定一个数组,先进行排序,然后给定一个数,利用二分法查找该数是否在数组中

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

int data[] = {21,43,566,89,10,9,55,22};
int size = sizeof(data)/sizeof(data[0]);
void sorder(int *p)
{
	int t,temp;
	int i,j;
	for(i = 0; i < size; i++)
	{
		t = i;
		for(j = i + 1; j < size; j++)
		{
			if(p[j] <= p[t])
			{
				t = j;
			}
		}
		temp = p[i];
		p[i] = p[t];
		p[t] = temp;
		
	}	
}
void dorder(int *p)
{
	int t,temp;
	int i,j;
	for(i = 0; i < size; i++)
	{
		t = i;
		for(j = i + 1; j < size; j++)
		{
			if(p[j] >= p[t])
			{
				t = j;
			}
		}
		temp = p[i];
		p[i] = p[t];
		p[t] = temp;
		
	}	
}
int com(int dtype,int num,int *p)//dtype=1就选取sorder,否则用dorder
{
	int count = 0;
	int left = 0;
	int right = size - 1;
	
	int i;
	if(dtype == 1)
	{
		sorder(p);
		while(left <= right)
		{
			int mid = (left + right)/2;
			count++;
			if(p[mid] == num)
			{
				return count;
			}
			else if(p[mid] > num)
			{
				right = mid - 1;;
			}
			else
			{
				left = mid + 1;
			}
			
		}
		return -1;
	}
	else
	{
		dorder(p);
		while(left <= right)
		{
			int mid = (left + right)/2;
			count++;
			if(p[mid] == num)
			{
				return count;
				
			}
			else if(p[mid] > num)
			{
				left = mid + 1;
			}
			else
			{
				right = mid - 1;
			}
			
		}
		return -1;
	}
	
 } 
int main()
{
	
	cout << com(2,9,data) << endl;
	return 0;
}

抢红包

#include <iostream>
#include <time.h>
#include <cstdlib>
using namespace std;

int main()
{
    int people,i,best = 0;
    double money,j = 0;
    cout << "the money:";
    cin >> money;
    cout << "the people:";
    cin >> people;
    float a[100];//最多100个人,得到100个人对应随机数
    float b[100];//存储每个人得到的钱
    float suma = 0;
    
    for(i = 0; i < people; i++)
    {
        a[i] = rand()%100;
        suma += a[i];
    }
    for(i = 0;i < people; i++)
    {
        b[i] = a[i]*money/suma;
        if (j <= b[i])
        {
            j = b[i];
            best = i;//手气最佳
        }
    }
    for(i = 0;i < people; i++)
    {
        printf("第%d个人得到%.2f钱:",i,b[i]);
        if (best == i)
        {
            cout << "(手气最佳)" << endl;
        }
        else
        {
            cout << endl;
        }
    }
    return 0;


}