C program to sort strings using pointers


Generally to sort the contents of an array one use bubble sort method. In this bubble sort method, the adjacent two elements are compared so that the largest element will be moved to the top of the array in a single iteration of inner for loop. In this way iteration by iteration top most element of the array will be discarded and bubble sort method is applied on the remaining elements. That’s why inner for loop iterates ‘(n-i)-1’ times and outer for loop iterates ‘n-1’ number of times. This program sorts the strings using a function call. The function call takes the pointer to the strings as argument. So modifications that are done on the pointers will be reflected on the actual strings. The program will sort strings using bubble sort method.

 C program to sort strings using pointers


Source code:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define COLS 50
void sort_words(char *a[], int n)
{
     int i,j;
     char *temp;
     for(i=0;i < n-1;++i)
     for(j=i+1;j < n;++j)
     if(strcmpi(a[i],a[j])>0)
     {
        temp=a[i];
        a[i]=a[j];
        a[j]=temp;
     }
}
int main()
{
	char w[10][COLS];
	char *wdptr[10];
	int i;
	for(i=0; i<10; ++i)
	{
	     gets(w[i]);         //Step 1
	     wdptr[i]=w[i];      //Step 2
	}
	printf("\n Before sorting the strings are.......\n");
	for(i=0; i<10; ++i)
	puts(w[i]);              //Step 3
	sort_words(wdptr,10);    //Step 4
	printf("\n After sorting the strings are.......\n");
	for(i=0; i<10; ++i)
	puts(wdptr[i]);             //Step 5
	return 0;
}


edit-code-image

Sample test cases:

1. hai
this
is
topoint
it
is
a
repository
of
c
Before sorting the strings are…….
hai
this
is
topoint
it
is
a
repository
of
c

After sorting the strings are…….
a
c
hai
is
is
it
of
repository
this
topoint

Explanation:

Step 1: The strings are read into the variable w[][] from the user using gets() function.
Step 2: The starting address of the strings in the variable w[][] are taken into wdptr[] variable. So one can directly access strings using this wdptr[] variable.
Step 3: This step displays the strings before the sorting.
Step 4: Function sort_words() is called from the main program. This function takes wdptr[] as arguments. So modifications done on this variable will be reflected on the main strings.
Step 5: Finally after function call, the sorted strings are displayed on the output screen using puts() function.

More Information:Sorting
Explore C Programs:C Programs