Thursday, 26 December 2019

How to sort string in C

How to sort string in c|sorting of string

Sorting is just arranging elements in a specific order. It can be increasing, decreasing numbers, sorting characters in lexicographical order, etc. Here we will find how to sort string. 


CODE-

#include <stdio.h>
#include <string.h>

void main () {
   char str[] = "helloworld";
   char t;

   int i, j;
   int n = strlen(str);

   printf("The string before sorting - %s \n", str);

   for (i = 0; i < n-1; i++) {
      for (j = i+1; j < n; j++) {
         if (str[i] > str[j]) {
            t = str[i];
            str[i] = str[j];
            str[j] = t;
         }
      }
   }
   
   printf("The string after sorting  - %s \n", str);
   }

Output-

The string before sorting - helloworld
The string after sorting - dehllloorw




No comments:

Post a Comment