
Ely M.
asked 12/18/20Programming Algorithm
Create an algorithm that allows the user to enter 20 names into a string array. sort the array in ascending (alphabetical) order and display its contents.
1 Expert Answer

Patrick B. answered 12/18/20
Math and computer tutor/teacher
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int (*CompareCallback) (void *, void *);
int CompareInt( void * rec1, void * rec2)
{
int iNum1 = * ((int*)rec1);
int iNum2 = * ((int*)rec2);
//printf(" comparing %d vs %d \n",iNum1,iNum2);
return(iNum1-iNum2);
}
int CompareStr(void * rec1, void * rec2)
{
//printf(" Comparing %s vs %s \n",(char*)rec1,(char*)rec2);
return (
strcmp(
(char*)rec1,
(char*)rec2
)
);
}
int CompareAmount( void * rec1, void * rec2)
{
double dblFlAmt1 = *((double *)rec1);
double dblFlAmt2 = *((double *)rec2);
int iReturn=0;
if (dblFlAmt1 != dblFlAmt2)
{
iReturn = (dblFlAmt1>dblFlAmt2) ? 1 : -1;
}
return(iReturn);
}
void BubbleSort ( void * array, int n, int recSize, CompareCallback compareFuncPtr)
{
int i,j;
char * A = (char*)array;
for (i=n-1; i>0; i--)
{
for (j=0; j<=i-1; j++)
{
char * curRecPtr = A + j * recSize;
char * nextRecPtr = A + (j+1)*recSize;
int iCompareReturn = compareFuncPtr((void*)curRecPtr,(void*)nextRecPtr);
if (iCompareReturn>0)
{
char * tempBuff = (char*) malloc(recSize);
//swaps if out of order
memcpy(tempBuff, curRecPtr, recSize);
memcpy(curRecPtr, nextRecPtr, recSize);
memcpy(nextRecPtr, tempBuff, recSize);
free(tempBuff);
} //swaps
} //for j
}//for i
} //BubbleSort
int main()
{
int iLoop=0;
char strs[20][255];
int iNums[10];
for (iLoop=0; iLoop<20; iLoop++)
{
printf(" Please input name # %d :>",(iLoop+1));
memset(strs[iLoop],0,255);
scanf("%s",strs[iLoop]);
//printf(" Name # %d is >%s< ",(iLoop+1),strs[iLoop]);
}
printf("\n-----------------------------------------------\n the strings \n");
BubbleSort(strs,20,255,CompareStr);
for (iLoop=0; iLoop<20; iLoop++)
{
printf("%s \n",strs[iLoop]);
}
printf("\n\n");
// IF YOU WANT THE GOLF SCORES, plese UNCOMMENT the next block !!!!
/*****
for (iLoop=0; iLoop<10; iLoop++)
{
printf("Please input the golf score %d :>",(iLoop+1));
scanf("%d",&iNums[iLoop]);
}
printf("\n----------------------------------------------- \n");
BubbleSort(iNums,10,sizeof(int),CompareInt);
for (iLoop=0; iLoop<10; iLoop++)
{
printf("%d \n",iNums[iLoop]);
}
*/
}
Still looking for help? Get the right answer, fast.
Get a free answer to a quick problem.
Most questions answered within 4 hours.
OR
Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.
Patrick B.
Here ya go... I apologize; I prefer to store the input in file rather than having to input the data every time Cheers!12/18/20