Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to Delete in a Sorted Array in c #2

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 58 additions & 0 deletions How to Delete in a Sorted Array in c
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// C program to implement delete operation in a
// sorted array
#include <stdio.h>

// To search a key to be deleted
int binarySearch(int arr[], int low, int high, int key);

/* Function to delete an element */
int deleteElement(int arr[], int n, int key)
{
// Find position of element to be deleted
int pos = binarySearch(arr, 0, n - 1, key);

if (pos == -1) {
printf("Element not found");
return n;
}

// Deleting element
int i;
for (i = pos; i < n - 1; i++)
arr[i] = arr[i + 1];

return n - 1;
}

int binarySearch(int arr[], int low, int high, int key)
{
if (high < low)
return -1;
int mid = (low + high) / 2;
if (key == arr[mid])
return mid;
if (key > arr[mid])
return binarySearch(arr, (mid + 1), high, key);
return binarySearch(arr, low, (mid - 1), key);
}

// Driver code
int main()
{
int i;
int arr[] = { 10, 20, 30, 40, 50 };

int n = sizeof(arr) / sizeof(arr[0]);
int key = 30;

printf("Array before deletion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);

// Function call
n = deleteElement(arr, n, key);

printf("\n\nArray after deletion\n");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
}