How can I get all matching values with a binary search? - c

Here is my code for finding the position of a value in a sorted array using a binary search. My problem is that the value may be present in my array more than one time, but my search only shows the position of the first match it finds. I want to output my all matching value's position. How can I solve my issue?
Thanks in advance.
#include<stdio.h>
#include<stdlib.h>
void aSort(int *a, int aLen){
int i, j;
for(i=0; i<aLen-1; i++){
for(j=i+1; j<aLen; j++){
if(a[i] > a[j]){
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
return;
}
void bSearch(int *a, int aSize, int key,int *rArr, int *ItemNum){
int start = 0;
int aEnd = aSize-1;
int mid = (start + aEnd) / 2;
*ItemNum = -1;
while(start<=aEnd){
if(key == a[mid]){
*ItemNum += 1;
rArr[*ItemNum] = mid;
break;
}else if(a[mid] < key){
start = mid + 1;
}else{
aEnd = mid - 1;
}
mid = (start + aEnd) / 2;
}
return;
}
int main(){
int n;
char i_type;
printf("Enter number of array element: \n");
scanf("%d", &n);
int a[n];
printf("Insert array element manual or automatic?\nIf manual press 'M' or press 'A' for automatic\n");
scanf("%*c%c", &i_type);
if(i_type == 'a' || i_type == 'A'){
printf("The array elements is:\n");
int i;
for(i=0; i<n; i++){
a[i] = rand()%100;
printf("%d ", a[i]);
}
}else{
printf("Enter %d integer value: ", n);
int i;
for(i=0; i<n; i++){
scanf("%d", &a[i]);
}
printf("The array elements is:\n");
for(i=0; i<n; i++){
printf("%d ", a[i]);
}
}
aSort(a, n);
printf("\nNow the array is in ascending order:\n");
int i;
for(i=0; i<n; i++){
printf("%d ", a[i]);
}
printf("\nEnter the key value which you want to find: ");
int key, numArr, rArr[n];
scanf("%d", &key);
bSearch(a, n, key, rArr, &numArr);
if(numArr == -1){
printf("Item not found!\n");
}else{
int i;
for(i=0; i<=numArr; i++)
printf("Your item found in %d position.\n", rArr[i]+1);
}
return 0;
}

If there are likely to be many repeated values: Do two binary searches, to find the positions of the start and the end of the run of "key" values. Don't terminate the search on exact match, and don't skip over mid; use < for the condition in one search and <= for the other. [The details will be tricky and may need some debugging for cases where the key isn't found or is at one end.]
If there are likely to be few repeated values: Do a single search to find the first occurrence. Then, scan linearly to find the "other end".

Related

printing the largest value in array

I was having a trouble regarding to printing out the largest number in array in c language and i don't know how to do it while using loop. Please help me thanks
here is my code
#include <stdio.h>
void main() {
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for (int i = 0; i < size; i++) {
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for (int i = size - 1; i >= 0; i--) {
printf("%d ", nums[i]);
}
for (int a = 0; a < size; a++) {
for (int i = 0; i < size; i++) {
if (nums[a] > nums[i]) {
Lnum = nums[a];
}
}
}
printf("\nLargest element = %d", Lnum);
}
The algorithm for determining the largest element in an array goes as follows.
Use the value of the first array element as a start value for the biggest number.
Go over the rest of the array and check for each element if it is a bigger number.
When a bigger number is found use the bigger number for further comparisons.
#include<stdio.h>
void main(){
int Lnum, size;
printf("Enter the size: ");
scanf("%d", &size);
int nums[size];
for(int i=0; i<size; i++){
scanf("%d", &nums[i]);
}
printf("\nReversed = ");
for(int i=size-1; i>=0; i--){
printf("%d ", nums[i]);
}
Lnum = nums[0]; // Assume first element to be the largest element
for(int a=1; a<size; a++){ // start loop with second element
if(Lnum < nums[a]) { // check if current element is larger
Lnum = nums[a]; // found larger element, it is now the largest element of all inspected element
}
}
printf("\nLargest element = %d", Lnum);
}
Output:
Enter the size: 3
1 2 3
Reversed = 3 2 1
Largest element = 3
...Program finished with exit code 0

Program not proceeding after taking array input in C

#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d ", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
When I run the code, I am only able to enter the elements of array and thus the program does not proceed further.
What's wrong with the code?
int n,a[n],element;
Is equivalent of saying
int n;
int a[n];
int element;
Notice something? You're declaring an array of variable size with an uninitialized variable n. This leads to unexpected behaviour. Declare your array after the value of n has been set!
int n,element;
scanf("%d", &n);
int a[n];
On observing your code,
#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d", &a[i]); // correction: here you had given space after %d...
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
you had given space scanf("%d ", &a[i]); after %d which should not be used, that's why your program is not proceeding after taking array input... I am assuming your binary search operation is correct and working fine...

Finding pairs in an array that are equal to an input value

I have to find out if there is any pair of i,j such that array[i]^2 + array[j]^2 == x^2
.
If there are such pairs, I need to print all such (i,j). Otherwise, print “There are no such pairs”.
#include <stdio.h>
int main(){
int size=10, i, x,j;
int Array[size];
printf("What is the value of x:");
scanf("%d",&x);
for(i=0;i<size;i++){
printf("Enter array value :");
scanf("%d",&Array[i]);
}
for(i=0;i<size;){
for(j=i+1;j<size;j++)
if((Array[i]*Array[i])+(Array[j]*Array[j])==x*x) //how do I complete this for loop?
}
return 0;
}
Yo're almost there, why weren't you incrementing the value of i? Keep a counter to count the matched pairs, then print those or if nothing is found print whatever you want.
#include <stdio.h>
int main() {
int size = 10, i, x, j;
int Array[size];
printf("What is the value of x:");
scanf("%d", &x);
for (i = 0; i < size; i++) {
printf("Enter array value :");
scanf("%d", &Array[i]);
}
int counter = 0;
for (i = 0; i < size; i++) {
for (j = i + 1; j < size; j++)
if ((Array[i] * Array[i]) + (Array[j] * Array[j]) == x * x) {
printf("%d %d\n", Array[i], Array[j]);
counter++;
}
}
if (!counter) {
printf("There are no such pairs\n");
}
return 0;
}

Adding element in sorted order in an array

I want to add the element in an array while entering it in a sorted manner. That means at the time of entering the new element in array, it will add its sorted state.
I have tried following examples, but I want to do it in an automatic manner. Can anyone help me, please?
my example
#include <stdio.h>
void main()
{
int a[20], n, item, i;
printf("Enter the size of the array");
scanf("%d", &n);
printf("Enter elements of the array in the sorted order");
for (i = 0; i<n; i++)
{
scanf("%d", &a[i]);
}
printf("\nEnter ITEM to be inserted : ");
scanf("%d", &item);
i = n - 1;
while (item<a[i] && i >= 0)
{
a[i + 1] = a[i];
i--;
}
a[i + 1] = item;
n++;
printf("\n\nAfter insertion array is :\n");
for (i = 0; i<n; i++)
{
printf("\n%d", a[i]);
}
getch();
}

Number of occurrence of an element in a sorted array

I want to find the number of occurrence of an element in a sorted array. I used BinarySearch logic to implement this. But I am not getting the correct output. I am using this logic
numberOfOccurrence = findLastOccurrence - firstOccurrence + 1
This is my code
#include<stdio.h>
int find_last(int a[],int n,int key)
{
int low = 0;
int high = n-1;
int result = -1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid]==key)
{
result = mid;
low = mid+1;
}
else if(key<a[mid])
high = mid-1;
else
low = mid+1;
}
return result;
}
int find_first(int a[],int n,int key)
{
int low = 0;
int high = n-1;
int result = -1;
while(low<=high)
{
int mid = (low+high)/2;
if(a[mid]==key)
{
result = mid;
high = mid-1;
}
else if(key<a[mid])
high = mid-1;
else
low = mid+1;
}
return result;
}
int find_count(int a[],int n,int x)
{
int first,last;
first = find_first(a,n,x);
last = find_last(a,n,x);
printf("\nLast index is %d",last+1);
printf("\nFirst index is %d",first+1);
printf("\nlast-first+1 is %d",last - first + 1);
return (last-first+1);
}
main()
{
int a[10],flag=0,n,x,count=0,i;
printf("\nEnter the number of elements ");
scanf("%d",&n);
printf("\nEnter %d elements ",n);
for(i=0;i<n;i++){
scanf("%d",&a[i]);
}
printf("\n Elements are \n");
for(i=0;i<n;i++){
printf("%d ",a[i]);
}
printf("\n Enter the key ");
scanf("%d",&x);
count = find_count(a,n,x);
printf("%d","\n The count is %d \n",count);
}
but some problem in the statement return (last-first+1);. It is returning some large values.
I tested in CFree with mingw and Visual Studio 2010.
printf("%d","\n The count is %d \n",count);
change it to :
printf(" The count is %d \n",count);
You connot put more than one " " in printf
You don't even need a binary search for this (and in any case the array would need to be sorted). A simple traverse of the array is all that is needed, whether or not it is sorted. Plus a little error checking for good form (GIGO), which makes this program look much bulkier than it would without. The key part of the code is only 3 lines.
#include<stdio.h>
#define NUMBERS 10
int main ( ) {
int a[NUMBERS], n, x, count=0, i;
printf("\nEnter the number of elements ");
if (1 != scanf("%d",&n))
return 1; // bad entry
if (1 > n || NUMBERS < n)
return 1; // number out of range
printf("\nEnter %d elements ", n);
for(i=0; i<n; i++){
if (1 != scanf("%d", &a[i]))
return 1; // illegal number
}
printf("\nElements are \n");
for(i=0; i<n; i++){
printf("%d ", a[i]);
}
printf("\nEnter the key ");
if (1 != scanf("%d", &x))
return 1; // bad entry
for(i=0; i<n; i++){ // <--- every element
if (x == a[i]) // <--- find matching key
count++; // <--- keep a tally
}
printf("\nThe count is %d\n", count); // (corrected) result
return 0;
}

Resources