#include<stdio.h>
#include<string.h>
int
main()
{
char
*str[]={
"Gona","Ram","Samy","Banta","Amita"
};
int
i,j;
char
*t;
for(i=0;i<5;i++)
{
for(j=i+1;j<5;j++)
{
printf("\nstr[i=%d]%s\t",i,str[i]);
printf("str[j=%d]%s\n",j,str[j]);
if(
( strcmp(str[i],str[j]) )>0)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
}
printf("\nstr[iiiiii=%d]%s\t",i,str[i]);
}
printf("Sorted
Names are:\n");
for(i=0;i<5;i++)
{
printf("%s\n",str[i]);
}
return
0;
}
/*
-bash-3.2$
vi strSort.c
-bash-3.2$
./a.out
str[i=0]Gona
str[j=1]Ram
str[i=0]Gona
str[j=2]Samy
str[i=0]Gona
str[j=3]Banta
str[i=0]Banta
str[j=4]Amita
str[iiiiii=0]Amita
str[i=1]Ram
str[j=2]Samy
str[i=1]Ram
str[j=3]Gona
str[i=1]Gona
str[j=4]Banta
str[iiiiii=1]Banta
str[i=2]Samy
str[j=3]Ram
str[i=2]Ram
str[j=4]Gona
str[iiiiii=2]Gona
str[i=3]Samy
str[j=4]Ram
str[iiiiii=3]Ram
str[iiiiii=4]Samy
Sorted Names are:
Amita
Banta
Gona
Ram
Samy
*/
//4a. sorting words in array without library function
#include<stdio.h>
#include<string.h>
int
main()
{
//below
str is static array of char ptrs so must be initialized
char
*str[]={
"san","sa",
"santa","santa",
"Amita","Amit",
"zan","xow"
};
int
i,j;
char
*t;
for(i=0;i<8;i++)
{
for(j=i+1;j<8;j++)
{
printf("\nstr[i=%d]%s\t",i,str[i]);
printf("str[j=%d]%s\n",j,str[j]);
if(
( strCmp(str[i],str[j]) )>0)
{
t=str[i];
str[i]=str[j];
str[j]=t;
}
}
printf("\nstr[iiiiii=%d]%s\t",i,str[i]);
}
printf("Sorted
Names are:\n");
for(i=0;i<8;i++)
{
printf("%s\n",str[i]);
}
return
0;
}
int
strCmp(char *s1,char *s2)
{
//if(*s1!='\0'&&*s2!='\0')
// 2
//{
while(
*s1-*s2==0 && (*s1!='\0' || *s2!='\0')) // 3
{
s1++;
s2++;
}
//}
return(*s1-*s2);
// 4
}
/*
-bash-3.2$
./a.out
str[i=0]san
str[j=1]sa
str[i=0]sa
str[j=2]santa
str[i=0]sa
str[j=3]santa
str[i=0]sa
str[j=4]Amita
str[i=0]Amita
str[j=5]Amit
str[i=0]Amit
str[j=6]zan
str[i=0]Amit
str[j=7]xow
str[iiiiii=0]Amit
str[i=1]san
str[j=2]santa
str[i=1]san
str[j=3]santa
str[i=1]san
str[j=4]sa
str[i=1]sa
str[j=5]Amita
str[i=1]Amita
str[j=6]zan
str[i=1]Amita
str[j=7]xow
str[iiiiii=1]Amita
str[i=2]santa
str[j=3]santa
str[i=2]santa
str[j=4]san
str[i=2]san
str[j=5]sa
str[i=2]sa
str[j=6]zan
str[i=2]sa
str[j=7]xow
str[iiiiii=2]sa
str[i=3]santa
str[j=4]santa
str[i=3]santa
str[j=5]san
str[i=3]san
str[j=6]zan
str[i=3]san
str[j=7]xow
str[iiiiii=3]san
str[i=4]santa
str[j=5]santa
str[i=4]santa
str[j=6]zan
str[i=4]santa
str[j=7]xow
str[iiiiii=4]santa
str[i=5]santa
str[j=6]zan
str[i=5]santa
str[j=7]xow
str[iiiiii=5]santa
str[i=6]zan
str[j=7]xow
str[iiiiii=6]xow
str[iiiiii=7]zan
Sorted Names are:
Amit
Amita
sa
san
santa
santa
xow
zan
*/
No comments:
Post a Comment