Question

In: Computer Science

Write a program to compare those two searching algorithms and also compare two sorting algorithms. You...

Write a program to compare those two searching algorithms and also compare two sorting algorithms. You need to modify those codes in the book/slides to have some counters to count the number of comparisons and number of swaps. In the main function, you should have an ordered array of 120 integers in order to test searching algorithms, and the other two identical arrays of 120integers not in order to test sorting algorithms. Display all counters in the main functions.

Counter for number of comparisons in linear search

Counter for number of comparisons in binary search

Counter for number of comparisons in bubble sort

Counter for number of swaps in bubble sort

Counter for number of comparisons in selection sort

Counter for number of swaps in selection sort

“modify those codes in the book/slides” means adding additional parameters for counters, and a few statements for increasement of counters. DO not delete any statement or change return type from the original functions.

No output in searching and sorting functions

No global variables are allowed except for constants.

--------------------------------------------------

//*****************************************************************
// The linearSearch function performs a linear search on an       *
// integer array. The array arr, which has a maximum of size      *
// elements, is searched for the number stored in value. If the   *
// number is found, its array subscript is returned. Otherwise,   *
// -1 is returned indicating the value was not in the array.      *
//*****************************************************************

int linearSearch(const int arr[], int size, int value)
{
   int index = 0;       // Used as a subscript to search array
   int position = -1;   // To record position of search value
   bool found = false; // Flag to indicate if the value was found

   while (index < size && !found)
   {
      if (arr[index] == value) // If the value is found
      {
         found = true;         // Set the flag
         position = index;     // Record the value's subscript
      }
      index++;                  // Go to the next element
   }
   return position;              // Return the position, or -1
}

------------------------------------------------------------------------

//***************************************************************
// The binarySearch function performs a binary search on an     *
// integer array. array, which has a maximum of size elements, *
// is searched for the number stored in value. If the number is *
// found, its array subscript is returned. Otherwise, -1 is     *
// returned indicating the value was not in the array.          *
//***************************************************************

int binarySearch(const int array[], int size, int value)
{
   int first = 0,             // First array element
       last = size - 1,       // Last array element
       middle,                // Mid point of search
       position = -1;         // Position of search value
   bool found = false;        // Flag

   while (!found && first <= last)
   {
      middle = (first + last) / 2;     // Calculate mid point
      if (array[middle] == value)      // If value is found at mid
      {
         found = true;
         position = middle;
      }
      else if (array[middle] > value) // If value is in lower half
         last = middle - 1;
      else
         first = middle + 1;           // If value is in upper half
   }
   return position;
}

---------------------------------------------------------------

//*****************************************************************
// The bubbleSort function sorts an int array in ascending order. *
//*****************************************************************
void bubbleSort(int array[], int size)
{
   int maxElement;
   int index;

   for (maxElement = size - 1; maxElement > 0; maxElement--)
   {
      for (index = 0; index < maxElement; index++)
      {
         if (array[index] > array[index + 1])
         {
            swap(array[index], array[index + 1]);
         }
      }
   }
}

//***************************************************
// The swap function swaps a and b in memory.       *
//***************************************************
void swap(int &a, int &b)
{
   int temp = a;
   a = b;
   b = temp;
}

-------------------------------------------------------------------------------------------

//********************************************************************
// The selectionSort function sorts an int array in ascending order. *
//********************************************************************
void selectionSort(int array[], int size)
{
   int minIndex, minValue;

   for (int start = 0; start < (size - 1); start++)
   {
      minIndex = start;
      minValue = array[start];
      for (int index = start + 1; index < size; index++)
      {
         if (array[index] < minValue)
         {
            minValue = array[index];
            minIndex = index;
         }
      }
      swap(array[minIndex], array[start]);
   }
}

//***************************************************
// The swap function swaps a and b in memory.       *
//***************************************************
void swap(int &a, int &b)
{
   int temp = a;
   a = b;
   b = temp;
}

Please comment in all-new lines of code, thank you

Solutions

Expert Solution

#include <bits/stdc++.h>
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 &cmp, int &swaps)
{
swaps = cmp = 0;
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++) {
cmp++;
if (arr[j] > arr[j + 1]) {
swaps++;
swap(&arr[j], &arr[j + 1]);
}
}
}


void selectionSort(int arr[], int n, int &cmp, int &swaps)
{
int i, j, min_idx;
swaps = cmp = 0;

// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++) {
cmp++;
if (arr[j] < arr[min_idx]) {
min_idx = j;
}
}

// Swap the found minimum element with the first element
swaps++;
swap(&arr[min_idx], &arr[i]);
}
}

int binarySearch(int arr[], int l, int r, int x, int &cmp)
{
cmp = 0;
while (l <= r) {
int m = l + (r - l) / 2;
cmp++;
// Check if x is present at mid
if (arr[m] == x)
return m;

// If x greater, ignore left half
if (arr[m] < x)
l = m + 1;

// If x is smaller, ignore right half
else
r = m - 1;
}

// if we reach here, then element was
// not present
return -1;
}

int linearSearch(int arr[], int n, int x, int &cmp)
{
cmp = 0;
int i;
for (i = 0; i < n; i++) {
cmp++;
if (arr[i] == x)
return i;
}
return -1;
}

int main()
{

int cmp = 0, swaps = 0;
int array1[120], array2[120], array3[120];

for (int i = 0; i < 120; ++i)
array1[i] = i;

srand(time(NULL));

// assigning random values to array2 and array 3
for (int i = 0; i < 120; ++i)
{
array2[i] = array3[i] = rand() % 1000;
}

// searching number present at index 93
linearSearch(array1, 120, array1[110], cmp);
cout << "Number of comparisions in Linear Search: " << cmp << endl;
// searching number present at index 93
binarySearch(array1, 0, 119, array1[110], cmp);
cout << "Number of comparisions in Binary Search: " << cmp << endl;

bubbleSort(array2, 120, cmp, swaps);
cout << "Number of comparisions in Bubble Sort: " << cmp << endl;
cout << "Number of swaps in Bubble Sort: " << swaps << endl;

selectionSort(array3, 120, cmp, swaps);
cout << "Number of comparisions in Selection Sort: " << cmp << endl;
cout << "Number of swaps in Selection Sort: " << swaps << endl;
return 0;
}

Output Screenshot:-

-----------------------------------

Please give me a UPVOTE. Thank you :)


Related Solutions

Write a C++ program to compare those two searching algorithms and also compare two sorting algorithms....
Write a C++ program to compare those two searching algorithms and also compare two sorting algorithms. You need to modify those codes in the book/slides to have some counters to count the number of comparisons and number of swaps. In the main function, you should have an ordered array of 120integers in order to test searching algorithms, and the other two identical arrays of 120integers not in order to test sorting algorithms. Display all counters in the main functions.Counter for...
Description: The goal of this assignment is to compare the empirical complexity of two sorting algorithms:...
Description: The goal of this assignment is to compare the empirical complexity of two sorting algorithms: a) Heap sort and b) Radix sort. Instructions: - Implement the above two sorting algorithms using Java or any other programming language. - Repeatedly generate random input instances containing 10, 50, 100, 500, 1000, 5000, 10000, 15000, … 50 000. The generated numbers must be between 0 and 100. - Execute both algorithms to sort the randomly generated arrays. - Compare the running time...
Problem Description Objective This practical will test your knowledge on sorting and searching algorithms. In this...
Problem Description Objective This practical will test your knowledge on sorting and searching algorithms. In this practical, you will be implementing a number of algorithms. Each of these algorithms will be constructed in a different class. You should make sure that you know the complexity of the algorithms you implement. Design Think of how you are going to solve the problem and test your implementation with the test cases you designed based on the stages below. Testing Hint: it’s easier...
Task: Write a program that implements several sorting algorithms and use it to demonstrate the comparative...
Task: Write a program that implements several sorting algorithms and use it to demonstrate the comparative performance of the algorithms for a variety of datasets. Background The skeleton program sorting.cpp contains a main function for testing the operation of several sort algorithms over various data sizes and dataset organisations. The program understands the following arguments: -i insertion sort -s selection sort (default) -q quicksort -a (already) sorted dataset -v reverse-sorted dataset -r random dataset (default) -n no sorting x generate...
For your initial post, utilizing credible sources, describe the various types of sorting and searching algorithms...
For your initial post, utilizing credible sources, describe the various types of sorting and searching algorithms and give an example of each other than the examples provided in the assigned readings. Apply algorithmic design and data structure techniques in developing structured programs by discussing time and space complexity in relation to whether using a sort algorithm is better than using a search algorithm. Does it really matter with the capabilities of computers today? Provide justification to support your answers.
Please use Java You have to write a programing for the following sorting algorithms in increasing...
Please use Java You have to write a programing for the following sorting algorithms in increasing order and print required steps in order to explain how your sorting algorithms work. 3. Implement the merge sort algorithm. With answers in this link (https://www.chegg.com/homework-help/questions-and-answers/write-programing-following-sorting-algorithms-increasing-order-print-required-steps-order--q53916147?trackid=PJ_TOK85), answer the above questions.
Comparing (Sort Algorithms) Both of the two sorting algorithms will do "sort" on arrays which would...
Comparing (Sort Algorithms) Both of the two sorting algorithms will do "sort" on arrays which would contain x randomly generated integers where the value of x would be 10000, 20000, 40000 and 80000 (inputs). The parts of the program should be followed as..... 1. Set x = 10000, randomly generate x integers. Call qsort function to sort these integers and get the execution time. 2. Randomly generate another x integers. Call your own sorting algorithm and get the execution time....
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove,...
Java Searching and Sorting, please I need the Code and the Output. Write a method, remove, that takes three parameters: an array of integers, the length of the array, and an integer, say, removeItem. The method should find and delete the first occurrence of removeItem in the array. If the value does not exist or the array is empty, output an appropriate message. (After deleting an element, the number of elements in the array is reduced by 1.) Assume that...
**Using Matlab** Make the program for Jacobi iteration method and compare solutions obtaned by two algorithms,...
**Using Matlab** Make the program for Jacobi iteration method and compare solutions obtaned by two algorithms, Jacobi-iteration method and Gaussian elimination.
Evaluate the performance in general on two real applications of sorting algorithms in parallel computing. Support...
Evaluate the performance in general on two real applications of sorting algorithms in parallel computing. Support your description with diagrams and examples where it is necessary.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT