Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<iostream>
- #include <stdio.h> /* printf, NULL */
- #include <stdlib.h> /* srand, rand */
- #include <time.h> /* time */
- #include <fstream>
- using namespace std;
- void selection_sort (int ar[], int size)
- {
- int min_ele_loc;
- for (int i = 0; i < size; ++i)
- {
- //Find minimum element in the unsorted array
- //Assume it's the first element
- min_ele_loc = i;
- //Loop through the array to find it
- for (int j = i + 1; j < size; ++j)
- if (ar[j] < ar[min_ele_loc])
- //Found new minimum position, if present
- min_ele_loc = j;
- //Swap the values
- int temp = ar[i];
- ar[i] = ar[min_ele_loc];
- ar[min_ele_loc] = temp;
- }
- }
- int binary_search(int array[],int first,int last, int search_key)
- {
- int index;
- if (first > last)
- index = -1;
- else
- {
- int mid = (first + last)/2;
- if (search_key == array[mid])
- index = mid;
- else
- if (search_key < array[mid])
- index = binary_search(array,first, mid-1, search_key);
- else
- index = binary_search(array, mid+1, last, search_key);
- } // end if
- return index;
- }// end binarySearch
- int linear_search(int a[],int size,int search_key){
- int i;
- for(i=0;i<size;i++)
- if(a[i] == search_key)
- return i;
- return -1;
- }
- int main(){
- ofstream myfile;
- int A[200],i,n;
- srand (time(NULL));
- for(i=0;i<200;i++){
- A[i] = rand()%200;
- printf("%d ",A[i]);
- }
- printf("\n");
- selection_sort(A,200);
- myfile.open ("output.txt");
- // myfile << "Writing this to a file.\n";
- for(i=0;i<200;i++){
- // A[i] = rand()%200;
- printf("%d ",A[i]);
- myfile << A[i]<<" ";
- }
- // myfile.open ("output.txt");
- // myfile << "Writing this to a file.\n";
- //myfile.close();
- cout<<"Enter an integer in between 1 to 200 (inclusive):";
- cin>>n;
- int index = binary_search(A,0,200,n);
- if(index == -1){
- cout<<"element not found";
- myfile << "Element not found in Binary Search";
- }
- else {
- cout<< "binary search results for "<<n<<" is in the index : "<<index<<endl;
- myfile<< "\nbinary search results for "<<n<<" is in the index : "<<index<<endl;
- }
- index = linear_search(A,200,n);
- if(index == -1){
- cout<<"element not found";
- myfile << "Element not found in linear Search";
- }
- else{
- cout<< "linear search results for "<<n<<" is in the index : "<<index<<endl;
- myfile<< "\nlinear search results for "<<n<<" is in the index : "<<index<<endl;
- }
- myfile.close();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement