Skip to content

Commit

Permalink
Completed code for finding rank of any element in two sorted subarrays.
Browse files Browse the repository at this point in the history
  • Loading branch information
singhpratyush committed Feb 14, 2016
1 parent f3944d2 commit 94c125c
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/lab2/3/numbers.txt
/lab2/numbers.txt
/lab2/3/a.out
/lab2/5/a.out
45 changes: 45 additions & 0 deletions lab2/5/find_rank.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#include <iostream>

using namespace std;

int position(int *arr, int element, int start, int end)
{
int actualStart = start;
while( start <= end )
{
int mid = (start + end)/2;
if(arr[mid] > element)
end = mid - 1;
else if(arr[mid] < element)
start = mid + 1;
else
return mid - actualStart + 1;
}
return end - actualStart + 1;
}

int main(void)
{
int size;
cin >> size;
int arr[size];

for(int i = 0 ; i < size ; i ++ )
cin >> arr[i];

int k, index_element;
cin >> k;

cin >> index_element;

if(index_element < k)
cout << index_element + position(arr, arr[index_element], k, size-1) + 1;
else if (index_element > k)
cout << index_element - k + position(arr, arr[index_element], 0, k-1) + 1;
else
cout << 1;

cout << endl;

return 0;
}

0 comments on commit 94c125c

Please sign in to comment.