Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Language Examples - Sorting Strings

C Language Examples - Sorting Strings

C Language Examples C Language Examples

Sort in lexicographical order.

Example

#include

<

stdio.h

#include

<

string.h

int

main

(

)

{

int

i

,

j

;

char

str

[

10

]

[

50

]

,

temp

[

50

]

;

printf

(

"

Enter 10 words:

\

n

"

)

;

for

(

i

=

0

;

i

<

10

; ++

i

)

{

scanf

(

"

%s[^

\

n]

"

,

str

[

i

]

)

;

}

for

(

i

=

0

;

i

<

9

; ++

i

)

{

for

(

j

=

i

1

;

j

<

10

; ++

j

)

{

if

(

strcmp

(

str

[

i

]

,

str

[

j

]

)

0

)

{

strcpy

(

temp

,

str

[

i

]

)

;

strcpy

(

str

[

i

]

,

str

[

j

]

)

;

strcpy

(

str

[

j

]

,

temp

)

;

}

}

}

printf

(

"

\

nAfter sorting:

\

n

"

)

;

for

(

i

=

0

;

i

<

10

; ++

i

)

{

puts

(

str

[

i

]

)

;

}

return

0

;

}

The output is:



Enter 10 words:

C

C++

Java

PHP

Python

Perl

Ruby

R

JavaScript

PHP



After sorting:

C

C++

Java

JavaScript

PHP

PHP

Perl

Python

R

Ruby

C Language Examples C Language Examples