Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that reads 20 names from a file called names.dat and stores them

ID: 3622836 • Letter: W

Question

Write a program that reads 20 names from a file called names.dat and stores them in two different arrays (eg names1, names2). Print the unsorted array then modify the selection sort routine so that it sorts the 20 names in the first array. Count how many comparisons are needed to sort the 20 names. Print the sorted array contents and the number of comparisons needed.

Next, sort the second array with the bubblesort routine. Count how many comparisons are needed to sort the array with bubblesort. Print the unsorted array and the sorted array as you did previously along with the number of comparisons needed.

Use functions for a well structured program and don't forget your name and program description.

Explanation / Answer

please rate - thanks

#include <iostream>
#include <fstream>
#include <string.h>
using namespace std;
bool getdata(string a[],int n);
void printarray(string a[],int n,string mess);
void selectionsort(string a[],int n);
void bubblesort(string a[],int n);
int main()
{string a[20],b[20];
int i;
if(getdata(a,20))
{for(i=0;i<20;i++)
b[i]=a[i];
printarray(a,20,"names before selection sort");
selectionsort(a,20);
printarray(a,20," names after selection sort");
printarray(b,20," names before bubble sort");
bubblesort(b,20);
printarray(b,20," names after bubble sort");
}
system("pause");
return 0;
}
void selectionsort(string a[], int n)
{ int i,j,index,compare=0;
string min,temp;
for(i=0;i<n-1; i++)
{index=i;
min=a[i];
for(j=i+1;j<n;j++)
{compare++;
if(min.compare(a[j])>0)
{index=j;
min=a[j];
}
}
temp=a[i];
a[i]=a[index];
a[index]=temp;
}
cout<<" In Selection sort There were "<<compare<<" comparisons ";

}
bool getdata(string a[],int n)
{ifstream input;
int i;
input.open("names.dat"); //open file
if(input.fail()) //is it ok?
{ cout<<"file did not open please check it ";
system("pause");
return false;
}
for(i=0;i<n;i++)
input>>a[i];
input.close();
return true;
}
void printarray(string a[],int n,string mess)
{int i;
cout<<mess<<endl;
for(i=0;i<n;i++)
cout<<a[i]<<" ";
cout<<endl;
}
void bubblesort(string a[],int n)
{int i,j,compare=0;
string temp;
for (i=0; i<n; i++)
for (j=0; j<n-1; j++)
{compare++;
if (a[j+1].compare(a[j])<0)
{temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
cout<<" In bubble sort There were "<<compare<<" comparisons ";
}