算法基础上机实验——2023.5.15

1.

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int a[310], n, k = 0;
    cin >> n;
    while (n != -99999)
    {
        a[k ++] = n;
        cin >> n;
    }
    cin >> n;
    for (int i = 0; i < k; i ++)
    {
        if (a[i] == n)
        {
            cout << i;
            return 0;
        }
    }
    cout << -1 << endl;
    return 0;
}

2.

方法 1 排序法

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
    int n;
    cin >> n;
    int a[100];
    for (int i = 0; i < 2 * n; i ++)
    {
        cin >> a[i];
    }
    sort(a, a + 2 * n);
    int ans = a[n - 1];
    cout << ans << endl;
    
    return 0;
}

方法 2 减治法

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

void median(int a[], int b[], int start1, int end1, int start2, int end2)
{
	if (start1 == end1)
	{
		cout << (a[start1] < b[start2] ? a[start1] : b[start2]);
		return;
	}
	int mid1 = (start1 + end1) / 2;
	int mid2 = (start2 + end2) / 2;
	double num1, num2;
	if ((start1 + end1) % 2 != 0)//n 为偶数
	{
		num1 = (a[mid1] + a[mid1 + 1]) / 2;
		num2 = (b[mid2] + b[mid2 + 1]) / 2;
	}
	else
	{
		num1 = a[mid1];
		num2 = b[mid2];
	}
	
	if (num1 == num2)
	{
		cout << num1;
		return;
	}
	else if (num1 < num2)
	{
		if ((start1 + end1) % 2 != 0)
		{
			mid1 ++;
		}
		median(a, b, mid1, end1, start2, mid2);
	}
	else
	{
		if ((start1 + end1) % 2 != 0)
		{
			mid2 ++;
		}
		median(a, b, start1, mid1, mid2, end2);
	}
}

int main()
{
	int n;
	int a[100], b[100];
	cin >> n;
	for (int i = 1; i <= n; i ++)
	{
		cin >> a[i];
	}
	for (int i = 1; i <= n; i ++)
	{
		cin >> b[i];
	}
	median(a, b, 1, n, 1, n);
	
	return 0;
}

3.

#include <cmath>
#include <cstdio>
#include <iostream>
#include <algorithm>

using namespace std;

int BinSearch(int r[], int n, int k)
{
	int mid, low = 0, high = n - 1;
	while (low <= high)
	{
		mid = (low + high) / 2;
		if (k < r[mid]) high = mid - 1;
		else if (k > r[mid]) low = mid + 1;
		else return mid + 1;
	}
	return 0;
}

int main()
{
	int n;
	cin >> n;
	int i, a[100];
	for (i = 0; i < n; i ++)
	{
		cin >> a[i];
	}
	int k;
	cin >> k;
	cout << BinSearch(a, n, k) << endl;
	
	return 0;
} 
posted on 2023-05-15 19:35  逆袭怪  阅读(16)  评论(0编辑  收藏  举报