In: Computer Science
Pet [0] = "dog" Pet[1] = "cat" Pet[2] = "bird" Pet[3] = "snake" Pet[4] = "duck" Pet[5] = "fish" Pet[6} = "rabbit' Pet[7] = "mouse" Pet[8] = "pony" Pet[9] = "frog" SA 18.) Write a program segment to sort the given array in alphabetical order using the bubble sort method. Raptor Format (Prelude to Programing 6th ed.)
C program to read N names, store them in the form of an array and sort them in alphabetical order using Bubble Sort.
#include <stdio.h>
#include <string.h>
void main()
{
char name[10][8], tname[10][8], temp[8];
int i, j, n;
//The number of names in the array
printf("Enter the value of n :- \n");
scanf("%d",
&n);
//Enter all the names in the array and they will
be stord in a 2-D array
printf("Enter %d names \n", n);
for (i = 0; i < n; i++)
{
scanf("%s", name[i]);
//copy name[i] to tnam[i] so tname[i] contains the data we
entered
strcpy(tname[i], name[i]);
}
//Sort the array using Bubble Sort
Mechanism
for (i = 0; i < n - 1
; i++)
{
for (j = i + 1; j < n; j++)
{
if (strcmp(name[i], name[j]) > 0)
{
strcpy(temp, name[i]);
strcpy(name[i], name[j]);
strcpy(name[j], temp);
}
}
}
//now name array will
contain the sorted information
//display the input
names and the sorted information
printf("Input Names\tSorted names\n");
printf("------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("%s\t\t%s\n", tname[i], name[i]);
}
}
Output:-
Enter the value of n:- 10 Enter 10 names Input Names Sorted names ------------------------------------------ dog bird cat cat bird dog snake duck duck fish fish frog rabbit mouse mouse pony pony rabbit frog snake