Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <windows.h>
- #include <mmsystem.h>
- #include <time.h>
- #include <iostream>
- #include <ctime>
- #include <cstdlib>
- using namespace std;
- int n = 0;
- int i = 0;
- int binarySearch(int *list1, int first, int last, int value) {
- cout << "please enter a value to search = ";
- cin >> value;
- int answer = -1;
- if (first <= last)
- {
- Sleep(1);
- int mid = (first + last) / 2;
- if (list1[mid] == value)
- {
- answer = mid;
- cout << "value found, the position in the array is" << mid << endl;
- cout << "value found, the value of the array is " << list1[mid] << endl;
- }
- else
- if (list1[mid] > value)
- answer = binarySearch(list1, first, mid - 1, value);
- else answer = binarySearch(list1, mid + 1, last, value);
- }
- else
- answer = -1;
- return answer;
- }
- void findAverage(int* list1) {
- int total = 0;
- double average = 0;
- clock_t begin = clock();
- for (i = 0; i < n; i++) { total += list1[i]; Sleep(1); }
- average = total / (float)n;
- clock_t end = clock();
- double elapsed = end - begin;
- cout << "average of the array is " << average << endl;
- cout << "time taken to calculate average is " << elapsed << " milliseconds " << elapsed / 1000 << "seconds" << endl;
- }
- void main() {
- #pragma comment(lib, "winmm.lib")
- cout << "please enter the amount of integers you want to generate " << endl;
- cin >> n;
- clock_t begin1 = clock();
- cout << endl; cout << "generating first array of sorted integers" << endl;
- int* list1 = new int [n];
- for (int i = 0; i < n; i++) {
- list1[i] = i * 3 + 1;
- cout << " " << list1[i];
- Sleep(1);
- }
- clock_t end1 = clock();
- cout << endl; cout << "generating 2nd array of random integers" << endl;
- clock_t begin2 = clock();
- int* list2 = new int[n];
- for (int i = 0; i < n; i++) {
- list2[i] = rand() % 10000;
- cout << " " << list2[i];
- Sleep(1);
- }
- clock_t end2 = clock();
- cout << endl;
- double elapsed1 = end1 - begin1;
- double elapsed2 = end1 - begin1;
- cout << "time taken to generate sorted array " << elapsed1 << " milliseconds " << elapsed1 / 1000 << "seconds" << endl;
- cout << "time taken to generate random array " << elapsed2 << " milliseconds " << elapsed2 / 1000 << "seconds" << endl;
- findAverage(list1);
- binarySearch(list1, 0, n-1, -1);
- system("PAUSE");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement