In: Computer Science
How can i bubble sort a sentence in a char array in c++
This is the prototype of the function:
char* sort(char string[], int numOfWords, int lengthOfWord);
This is the testing code in the main file:
char words[] = "CAT FAT BAT HAT RAT";
printf("Before sort: t%s\n";words);
char result = sort(words; 5; 3);
printf("After sort : t%s\n"; result);
Expected output:
Before sort: CAT FAT BAT HAT RAT
After sort: BAT CAT FAT HAT RAT
#include<bits/stdc++.h>
using
namespace
std;
#define MAX 100
void
sort(
char
arr[][MAX],
int
n)
{
char
temp[MAX];
for
(
int
j=0; j<n-1; j++)
{
for
(
int
i=j+1; i<n; i++)
{
if
(
strcmp
(arr[j], arr[i]) >
0)
{
strcpy
(temp,
arr[j]);
strcpy
(arr[j],
arr[i]);
strcpy
(arr[i],
temp);
}
}
}
}
int
main()
{
char
arr[][MAX] =
{"
CAT","FAT","BAT","HAT","RAT"};
int
n
=
sizeof
(arr)/
sizeof
(arr[0]);
sortStrings(arr,
n);
printf
(
"Strings
in sorted order are : "
);
for
(
int
i=0; i<n; i++)
printf
(
arr[i],",");
return
0;
}