1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
#include <iostream>
using namespace std;
int search (int*, int);
float mean(int*, int);
int location(int*, int, int);
void sort(int*, int);
int main()
{
int num[50];
int numEle, a, l;
cout << "Input number of elements: ";
cin >> numEle;
for (int i = 0; i < numEle; i++)
{
cout << "Input element #"<<i+1<<": ";
cin >> num[i];
}
sort(num, numEle);
a = search(num, numEle);
for (int j = 0; j < numEle; j++)
{
cout << num[j]<<" ";
}
l = location(num, numEle, a);
if (a != -1)
{
cout << "Number searched: "<<a<<endl;
cout << "Location of number searched: Index number "<<l<<endl;
}
else cout << "The number searched does not exist."<<endl;
cout << "The average of the elements is: "<<mean(num, numEle)<<endl;
return 0;
}
void sort(int array[], int element)
{
int temp;
for (int i = element - 1; i > 0; i--)
{
for (int k = 0; k < element; k++)
{
if (array[k] > array[k+1])
{
temp = array[k+1];
array[k+1] = array[k];
array[k] = temp;
}
}
}
}
int search(int arr[], int num)
{
int ele;
int first = 0, last = num-1, mid;
bool found = false;
cout << "Select element to be searched: ";
cin >> ele;
while ((first <= last) && (found == false))
{
mid = (first+last)/2;
if (ele > arr[mid])
first = mid+1;
else if (ele < arr[mid])
last = mid-1;
else
{
found = true;
}
}
if (found == true)
{
return ele;
}
else return -1;
}
float mean(int arr[], int num)
{
int temp, ave;
for (int i =0; i < num; i++)
{
temp = temp + arr[i];
}
ave = temp/num;
return ave;
}
int location(int arr[], int num, int ele)
{
int first = 0, last = num-1, counter = 0;
bool found = false;
while (found == false)
{
if (ele != arr[counter])
counter++;
else if (ele == arr[counter])
{
counter++;
found = true;
}
}
return counter;
}
|