Lyo001 / gg

0 stars 0 forks source link

Binary search #5

Open Lyo001 opened 2 weeks ago

Lyo001 commented 2 weeks ago

include

int main() { int n, i, target, found = -1; printf("Enter the number of elements: "); scanf("%d", &n);

int arr[n];
printf("Enter the elements: ");
for (i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

printf("Enter the target element: ");
scanf("%d", &target);

for (i = 0; i < n; i++) {
    if (arr[i] == target) {
        found = i;
        break;
    }
}

if (found != -1) {
    printf("Element found at index %d\n", found);
} else {
    printf("Element not found\n");
}

return 0;

}

Lyo001 commented 2 weeks ago

include

int main() { int n, target, left = 0, right, mid, found = -1; printf("Enter the number of elements: "); scanf("%d", &n);

int arr[n];
printf("Enter the sorted elements: ");
for (int i = 0; i < n; i++) {
    scanf("%d", &arr[i]);
}

printf("Enter the target element: ");
scanf("%d", &target);

right = n - 1;
while (left <= right) {
    mid = left + (right - left) / 2;
    if (arr[mid] == target) {
        found = mid;
        break;
    } else if (arr[mid] < target) {
        left = mid + 1;
    } else {
        right = mid - 1;
    }
}

if (found != -1) {
    printf("Element found at index %d\n", found);
} else {
    printf("Element not found\n");
}

return 0;

}