For c++ Write a version of the sequential search algorithm that carn be used to
ID: 3718997 • Letter: F
Question
For c++
Write a version of the sequential search algorithm that carn be used to search a sorted list. Write a program to test the sequential search algorithm. Use either the function bubbleSort or insertionSort to sort the list before the search. Your program should prompt the user to enter 10 digits and then prompt the user to enter a digit to search if the list contains this digit, output its position to the console x is found at position y If the digit is not contained in the list, output the following: x is not in the listExplanation / Answer
Following is the answer:
#include <iostream>
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
for (i = 0; i < n-1; i++)
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
swap(&arr[j], &arr[j+1]);
}
void search(int arr[], int n, int x){
int k;
int index = 0;
for(k=0 ; k< n-1 ; k++)
{
if(arr[k] == x){
index = k;
}
}
if(index == 0){
cout<< k << " is not in the list.";
}else{
cout<< k <<" is found at position " << index;
}
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i=0; i < size; i++)
cout<< arr[i] << " ";
cout<<" ";
}
// Driver program to test above functions
int main()
{
int size;
int search;
cout<<"Enter the size of an array";
cin>>size;
int x;
cout<<"Enter the array values";
int arr[] = {64, 34, 25, 12, 22, 11, 90};
for(x= 0;x< size ; x++ ){
cin>>arr[x];
}
cout<<"Enter the value for search ";
cin>>search;
int n = sizeof(arr)/sizeof(arr[0]);
bubbleSort(arr, n);
cout<<"Sorted array: ";
printArray(arr, n);
search(arr,n,search);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.