Write a program that creates three identical arrays list1 li

Write a program that creates three identical arrays, list1, list2, and list3, of 5000 elements. The program then sorts list1 using bubble sort, list2 using selection sort, and list3 using insertion sort and outputs the number of comparisons and item assignments made by each sorting algorithm.

Please use the file names listed below since your file will have the following components:
Ch18_Ex15.cpp
searchSortAlgorithms.h

Solution


#include <fstream>
#include <iostream>
#include<string>
#include <time.h>
#include<stdio.h>

void bubbleSort(int a[], int n)
{
   int x;
   int count=0;
   for (int i = 0 ; i < ( n - 1 ); i++)
   {
   for (int j = 0 ; j < n - i - 1; j++)
   {
   if (a[j] > a[j+1]) /* For decreasing order use < */
   {
x = a[j];
   a[j] = a[j+1];
   a[j+1] = x;
   count++;
   }
   }
   }
   cout <<\"Bubble sort took \"<<count <<\" Comparisons\"<<endl;
}
void selectionSort(int a[], int n)
{

   int min,t, count=0;

   for (int i=0; i < n-1; i++)
   {
   min = i;      
       for (int j=i+1; j < n; j++)
       {

           if (a[j] < a[min])
           {
               min=j;
               count++;
           }
  
       }
if (min != i)
{
t = a[i];
a[i] = a[min];
a[min] = t;

}
   }
   cout <<\"Selection sort took \"<<count <<\" Comparisons\"<<endl;
}
void insertionSort(int a[], int n)
{

   int min,t, count=0;

   for (int i = 1; i < n; i++)
{
for (int j = i; j >= 1; j--)
{
if (a[j] < a[j-1])
{
t = a[j];
a[j] = a[j-1];
a[j-1] = t;
count++;
}
else
break;
}
}
   cout <<\"Insertion sort took \"<<count <<\" Comparisons\"<<endl;
}

int main()
{
   int list1[5000], list2[5000], list3[5000];
   srand (time(NULL));
   for(int i=0;i<5000;i++)
   {
       list1[i]=rand() % 5000 + 1;
   }
   list2=list1;
   list3=list1;
  
   bubbleSort(list1, 5000);
   selectionSort(list2, 5000);
   insertionSort(list3, 5000);
   for(int i=0;i<5000;i++)
   {
       cout << list3[i]<< endl;
   }
}

Write a program that creates three identical arrays, list1, list2, and list3, of 5000 elements. The program then sorts list1 using bubble sort, list2 using sele
Write a program that creates three identical arrays, list1, list2, and list3, of 5000 elements. The program then sorts list1 using bubble sort, list2 using sele

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site