adsense

Hii, welcome to my site. My name is Om prakash kartik. This blog helps you to learn programming languages concepts.

Program in C++ to search an element in array

Program in C++ to search an element in array

  • Search given data in an array using linear search - Sorted array


 
#include<iostream>
 using namespace std;
 void sort(int arr[], int n){ // Insertion sort
    int i, j, temp;
    for(i = 1; i < n; i++){
        temp = arr[i];
        for(j = i - 1; j >= 0 && temp < arr[j]; j--){
            arr[j + 1] = arr[j];
        }
        arr[j + 1] = temp;
    }
 }
 void Find(int arr[], int n, int data){ // find data using sorted array
    int i;
    sort(arr,n);
    for(i = 0; i < n; i++){
        if(data == arr[i] || data == arr[n - 1 - i]){
            cout<<endl<<"Data is found.";
            return;
        }
        else if(data < arr[i] || data > arr[n - 1 - i]){
            cout<<endl<<"Data is not found.";
            return;
        }
    }
 }
 void show(int arr[], int n){
    cout<<endl<<"Elements of array is ";
    for(int i = 0; i < n; i++){
        cout<<"   "<<arr[i];
    }
 }
 int main()
 {
    int arr[] = { 64, 10, 15, 45, 60, 24, 55};
    show(arr,7);
    Find(arr,7,45);
    Find(arr,7,5);
    Find(arr,7,65);
    Find(arr,7,60);
    return 0;
 }
Output :-




Post a Comment

0 Comments