Sorting Algorithm in C

Sorting characters and numbers is a basic task and writing your own function for that is a great way to learn programming. Also, as far as I know, there’s no such functions included in standard C libraries, so you have to write your own code anyways.

The algorithm I wrote loops through an array and compares each element to the next one. If the next element is greater than the previous one, the two swap places – if the desired order is ascending. The idea is very simple, but writing properly working functions requires some experimentation.

I wrote my functions in a header file, because including your own .h file in a program and seeing your functions work is awesome. It is also convenient to reuse, but nothing beats the experience!

My header file starts with declaring some variables and the functions:

char asc = 'a', desc = 'd';           //variables to define sort order in functions
void sorts(char arr[], char o);       //function for sorting characters
void sortd(int arr[], int n, char o); //function for sorting digits
int slength(char s[]);                //function for determining string length

The logic for sorting characters and numbers is the same, but there is an important difference in implementation. If you sort characters, you can use the strlen function in the string.h library to determine how many times the loops in the algorithms should run, but I wrote my own function for that. That’s why my string sorting function has only two parameters: the string array and a character determining the order. If you sort numbers, the function either needs a plain integer parameter or you have to play around with pointers to determine the length of the array. I chose the simpler method for now. The reason is, that in digit arrays there is no '\0' special character to mark the end of the array as with string arrays. You can determine the length of a digit array using this trick:

int number_of_elements = sizeof(array) / sizeof(array[0])

However, if you pass number_of_elements into a function, it won’t work. You need to use pointers and it adds complexity I feel unnecessary for now. On the opposite, switching sort order is extremely simple, as you will see in the code.

Function to sort a string:

void sorts(char arr[], char o) //o determines sort order
{
	int i, j, temp;
	int length = slength(arr); //determine string length

	for (i = 0; i < length-1; i++)
	{
		for (j = 0; j < length-1; j++)
		{
			if (o == 'a') //ascending order char asc = ‘a’
			{
				if (arr[j] > arr[j+1]) //if element j is greater than j+1
				{
					temp = arr[j];     //save j in temp
					arr[j] = arr[j+1]; //swap j with j+1
					arr[j+1] = temp;   //replace j+1 with original j
				}
			}
			if (o == 'd') //descending order char desc = ‘d’
			{
				if (arr[j] < arr[j+1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

Function to sort numbers:

void sortd(int arr[], int n, char o)
{
	int i, j, temp;

	for (i = 0; i < n-1; i++)
	{
		for (j = 0; j < n-1; j++)
		{
			if (o == 'a')
			{
				if (arr[j] > arr[j+1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
			if (o == 'd')
			{
				if (arr[j] < arr[j + 1])
				{
					temp = arr[j];
					arr[j] = arr[j+1];
					arr[j+1] = temp;
				}
			}
		}
	}
}

Function to determine string length:

int slength(char s[])
{
	int i;
	for (i = 0; i < 100; i++)
	{
		if (s[i] == '\0')
		{
			return i;
		}
	}
}

I use CodeBlocks and if you want to include your own header file in source code, you have to configure the IDE to look for it in the right place: Settings -> Compiler -> Search directories -> Add – at least I think. Save your functions in a .h file and add its folder here.

An exaple code for sorting digits:

#include <stdio.h>
#include <stdlib.h>
#include <sort.h> //my custom header file including the sorting functions
#define NELEM(x) (sizeof(x) / sizeof(x[0]))
//NELEM for determining the number of elements in an array
//but you can’t pass its result into the function as it is
//because it won’t work for some C reason

int main()
{
    int i;
    int nums[5] = {3,5,1,7,2};

    printf("Unsorted array: ");
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n\n");
    printf("Sorted array in ascending order: ");
    sortd(nums,5,asc);
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n\n");
    printf("Sorted array in descending order: ");
    sortd(nums,5,desc);
    for (i = 0; i<NELEM(nums); i++)
    {
        printf("%d", nums[i]);
    }
    printf("\n");
    return 0;
}
Sorting digit array

Sorting a digit array

An example code to sort a string:

#include <stdio.h>
#include <stdlib.h>
#include <sort.h>
#define MAX 4

int main()
{
    char text[MAX];
    printf("Type string (max %d characters): ", MAX);
    scanf("%s", text);
    sorts(text, asc);
    printf("\nSorted string in ascending order: %s\n", text);
    sorts(text, desc);
    printf("\nSorted string in descending order: %s\n", text);

    return 0;
}
Sorting a sting

Sorting a sting

Programming is awesome!

Advertisements

I enjoy microcontroller programming (AVR), programming in C/C#, playing with electronics, the Raspberry Pi and Arduino. My other passion is for IT - virtualization, PowerShell, servers and so on.

Tagged with: , ,
Posted in Programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Archives

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 167 other followers

%d bloggers like this: