|
| 1 | +//DS LAB Assignment-4 Maintaining Sorted Array by Aayush Patel 2K20/CO/11 |
| 2 | +#include <stdio.h> |
| 3 | +void insert(int *a, int x, int n) |
| 4 | +{ |
| 5 | + int i; |
| 6 | + for (i = n - 1; (a[i] > x) && i >= 0; i--) |
| 7 | + { |
| 8 | + a[i + 1] = a[i]; |
| 9 | + } |
| 10 | + a[i + 1] = x; |
| 11 | +} |
| 12 | +int deleteelement(int *a, int index, int n) |
| 13 | +{ |
| 14 | + if (index >= n) |
| 15 | + return -1; |
| 16 | + for (int i = index; i < n - 1; i++) |
| 17 | + a[i] = a[i + 1]; |
| 18 | + return 1; |
| 19 | +} |
| 20 | +int search(int *a, int k, int n) |
| 21 | +{ |
| 22 | + int l = 0,h = n; |
| 23 | + while (l <= h) |
| 24 | + { |
| 25 | + int m =l+(h-l)/2; |
| 26 | + if (a[m] == k) |
| 27 | + return m; |
| 28 | + else if (k > a[m]) |
| 29 | + l = m + 1; |
| 30 | + else if (k < a[m]) |
| 31 | + h = m - 1; |
| 32 | + } |
| 33 | + return -1; |
| 34 | +} |
| 35 | + |
| 36 | +void display(int *a, int n) |
| 37 | +{ |
| 38 | + printf("Displaying Sorted Array List :\n"); |
| 39 | + for (int i = 0; i < n; i++) |
| 40 | + printf("%d ", a[i]); |
| 41 | + printf("\n"); |
| 42 | +} |
| 43 | +int main() |
| 44 | +{ |
| 45 | + int op, n = 0; |
| 46 | + int a[30]; |
| 47 | + do |
| 48 | + { |
| 49 | + printf("\nOperations Menu Options:\n"); |
| 50 | + printf("1.Insert\n"); |
| 51 | + printf("2.Delete\n"); |
| 52 | + printf("3.Search\n"); |
| 53 | + printf("4.Display\n"); |
| 54 | + printf("5.Exit\n"); |
| 55 | + int x; |
| 56 | + printf("Enter your op:"); |
| 57 | + scanf("%d", &op); |
| 58 | + switch (op) |
| 59 | + { |
| 60 | + case 1: |
| 61 | + printf("Enter element to be inserted:"); |
| 62 | + scanf("%d", &x); |
| 63 | + insert(a, x, n); |
| 64 | + n++; |
| 65 | + printf("Element inserted.\n"); |
| 66 | + break; |
| 67 | + case 2: |
| 68 | + printf("Enter element's index to be deleted:"); |
| 69 | + scanf("%d", &x); |
| 70 | + if (deleteelement(a, x, n) == -1) |
| 71 | + printf("Invalid Index\n"); |
| 72 | + else |
| 73 | + { |
| 74 | + printf("Element Deleted.\n"); |
| 75 | + n--; |
| 76 | + } |
| 77 | + break; |
| 78 | + case 3: |
| 79 | + printf("Enter element to be searched:"); |
| 80 | + scanf("%d", &x); |
| 81 | + if (search(a, x, n) == -1) |
| 82 | + printf("Element Not Found\n"); |
| 83 | + else |
| 84 | + printf("Element found at %dth position\n", search(a, x, n)); |
| 85 | + break; |
| 86 | + case 4: |
| 87 | + display(a, n); |
| 88 | + break; |
| 89 | + default: |
| 90 | + printf("Exit!"); |
| 91 | + break; |
| 92 | + } |
| 93 | + } while (op != 5); |
| 94 | + return 0; |
| 95 | +} |
0 commit comments