This blog is under construction

Sunday 26 May 2013

C Program To Implement Linear Search On Sorted & Unsorted Array

Linear Search is a searching technique where the element to be found is searched sequentially on the sorted or unsorted arrays.

See Also:
C Program To Implement Binary Search
C Program To Implement Linear Search On Sorted & Unsorted Array
C Program To Implement Brute Force Algorithm
C program To Implement Knuth-Morris-Pratt Algorithm

Example Program to Implement Linear Search On Sorted & Unsorted Array(in C):



  #include <stdio.h>
  #include <stdlib.h>

  int main() {
        int i, j, n, val, *data, index = -1, temp;

        printf("Enter the no of elements:");
        scanf("%d", &n);

        data = (int *)malloc(sizeof(int) * n);
        for (i = 0; i < n; i++) {
                printf("data[%d]:", i);
                scanf("%d", &data[i]);
        }

        printf("Enter the element to be searched:");
        scanf("%d", &val);

        printf("Unsorted Array:\n");
        for (i = 0; i < n; i++) {
                printf("%d  ", data[i]);
                if (data[i] == val)
                        index = i + 1;
        }
        printf("\n");

        if (index == -1) {
                printf("Given value is not present in the given Array\n");
                exit(0);
        } else {
                printf("%d is at the postion %d\n", data[index - 1], index);
        }

        for (i = 0; i < n - 1; i++) {
                for (j = i + 1; j < n; j++) {
                        if (data[i] > data[j]) {
                                temp = data[i];
                                data[i] = data[j];
                                data[j] = temp;
                        }
                }
        }
        printf("\nSorted Array:\n");
        for (i = 0; i < n; i++) {
                printf("%d ", data[i]);
                if (data[i] == val)
                        index = i + 1;
        }
        printf("\n%d is at the position %d in sorted array\n", data[index - 1], index);
        return 0;
  }



  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter the no of elements:8
  data[0]:100
  data[1]:50
  data[2]:75
  data[3]:25
  data[4]:85
  data[5]:15
  data[6]:95
  data[7]:35
  Enter the element to be searched:95

  Unsorted Array:
  100  50  75  25  85  15  95  35  
  95 is at the postion 7

  Sorted Array:
  15 25 35 50 75 85 95 100 
  95 is at the position 7 in sorted array



No comments:

Post a Comment