I have used Bubblesort for my Implementation:
Avinash
#include "stdio.h"
#include "stdlib.h"
void StringBubbleSort(char **aStringNames);
void DisplayArray(char **aArrayPtr);
void InputArray(char **aArrayPtr);
int iTotalNames;
void MyStrCpy(char *Src ,const char *Dest);
int MyStrcmp(char *string1 , char *string2);
void main()
{
char SZTemp[50];
char **aArrayPtr = NULL;
printf("ENTER THE TOTAL NO OF NAMES TO BE ENTERED:");
scanf("%d",&iTotalNames);
char a = getchar();
aArrayPtr = (char **)malloc(sizeof(int)*iTotalNames);
InputArray(aArrayPtr);
StringBubbleSort(aArrayPtr );
DisplayArray(aArrayPtr);
}
void InputArray(char **aArrayPtr)
{
int iCount = 0;
for(iCount=0; iCount
aArrayPtr[iCount] = (char *)malloc(sizeof(char)* 20);
printf("\nEnter the Names: \n");
for(iCount=0; iCount
fgets(aArrayPtr[iCount], 20, stdin);
}
void DisplayArray(char **aArrayPtr)
{
int iCount = 0;
for (iCount=0; iCount
{
fputs(aArrayPtr[iCount], stdout);
}
printf("\n");
}
void StringBubbleSort(char **aStringNames)
{
int iPass,iCompare;
char temp[20];
for(iPass = 1; iPass
{
for(iCompare = 0; iCompare
{
if((MyStrcmp(aStringNames[iCompare],aStringNames[iCompare+1])) == 1)
{
MyStrCpy(temp,aStringNames[iCompare+1]);
MyStrCpy(aStringNames[iCompare+1],aStringNames[iCompare]);
MyStrCpy(aStringNames[iCompare],temp);
}
}
}
}
int MyStrcmp(char *string1 , char *string2)
{
while((*string1 == *string2) && (*string1 != NULL))
{
string1++;
string2++;
}
if(*string1 == *string2)
return 0;
else if(*string1 > *string2)
return 1;
else
return -1;
}
void MyStrCpy(char *Dest ,const char *Src)
{
while(*Src !=0 )
{
*Dest = *Src;
Dest++;
Src++;
}
*Dest = '\0';
}
2 comments:
very simple selection sor approch:
#include "stdafx.h"
int main(int argc, char* argv[])
{
char unsorted[20],temp;
int i, j;
printf("Enter a String:");
printf("\n");
scanf("%s",unsorted);
printf("\n");
for(i = 0; unsorted[i]!= NULL; i++ )
{
for (j = i+1; unsorted[j]!= NULL; j++ )
{
if(unsorted[j]<unsorted[i])
{
temp = unsorted[j];
unsorted[j] = unsorted[i];//swap
unsorted[i] = temp;
}
}
}
printf("sorted String \n%s", unsorted);
printf("\n");
return 0;
}
From : Arpit
avinash.......you forgot to free the allocated memory......
Post a Comment