#include <iostream>
using namespace std;
void print_array(int* array, int size)
{
for (int i=0; i<size; i++)
cout << array[i] << " ";
cout << endl;
}
void selection_sort(int* array, int size)
{
for (int i=0; i<size; i++)
for (int j=i; j<size; j++)
{
if (array[j] < array[i])
{
int temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
// O(n)
void cal_elems_of_sum(int* array, int size, int sum)
{
int i = 0, j = size - 1;
bool found = false;
while (i < j)
{
if (array[i] + array[j] < sum)
i++;
else if (array[i] + array[j] > sum)
j--;
else
{
found = true;
cout << array[i] << " + " << array[j] << " = " << sum << endl;
i++;
j--;
}
}
if (!found)
{
cout << "No solution found." << endl;
}
}
void main()
{
int* array;
int size;
cout << "Input the size:" << endl;
cin >> size;
array = new int[size];
for (int i=0; i<size; i++)
array[i] = rand()%100;
print_array(array, size);
selection_sort(array, size);
print_array(array, size);
int sum;
cout << "Input the sum you want:" << endl;
cin >> sum;
cal_elems_of_sum(array, size, sum);
delete[] array;
}
在排序数组中寻找两个数使其和等于给定数
最新推荐文章于 2022-11-08 17:19:51 发布