Created
October 3, 2016 11:41
-
-
Save samair/1e5808ba1c26dd2a682923dfe7bd422f to your computer and use it in GitHub Desktop.
Sorting Algorithms
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
// Input a sorted array of integres. | |
// Out put searcha and give the position of the search element | |
int search(int arrayToSearch[], int startPos, int size , int searchMe) | |
{ | |
// find the middle of the array | |
cout <<"New Array Size:"<<size<<endl; | |
int middlePos = (startPos + size )/2; | |
if (size >=1) | |
{ | |
//Check if the element to be searched is greater than the middle element | |
if (searchMe < arrayToSearch[middlePos]) | |
{ | |
//Start searching left | |
return search(arrayToSearch,0,middlePos,searchMe); | |
} | |
else if (searchMe > arrayToSearch[middlePos]) | |
{ | |
startPos = middlePos; | |
return search(arrayToSearch,startPos+1,size-1,searchMe); | |
} | |
else if (searchMe == arrayToSearch[middlePos]) | |
{ | |
cout<<"Found Value :"<< arrayToSearch[middlePos] <<endl; | |
cout<<"position is :"<< middlePos<<endl; | |
return middlePos; | |
} | |
} | |
return -1; | |
} | |
int main() | |
{ | |
int arrayToUse[] = {7,9,14,22,100,190,300}; | |
int sizeOfArray= (sizeof(arrayToUse) / sizeof(int)); | |
cout<<"Sizeof Array :"<< sizeOfArray <<endl; | |
int posOfElement = search(arrayToUse,0,sizeOfArray-1,100); | |
cout<<"position is :"<< posOfElement <<endl; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment