Sorting array elements with C language

UPDATE 17:19: it seems that the program I implemented today uses a kind of Bubble Sort algorithm, give it a try, it’s quite interesting!

After 3 long days studying C, I think I’ve assimilated a good knowledge base for the incoming semester.
So there is a tiny C program that sorts the elements of a given integer array, using pointers:

Download the source code (well commented)

#include <stdio.h>
void sortArray(int *firstElement, int *lastElement);
void swapArrayElements(int *firstElement, int *secondElement);
void printArray(int array[], int arraySize);
 
void sortArray(int *firstElement, int *lastElement){
	int *currentElement = firstElement;
	while (firstElement != lastElement){
		while(currentElement != lastElement){
			if(*currentElement < *firstElement){
				swapArrayElements(currentElement,firstElement);
			}
			currentElement++;
		}
		firstElement++;
		currentElement = firstElement;
	}
}
 
void swapArrayElements(int *firstElement, int *secondElement){
	int tmp;
	tmp = *firstElement;
	*firstElement = *secondElement;
	*secondElement = tmp;
}
 
void printArray(int array[], int arraySize){
	int counter = 0;
	while(counter<arraySize){
		printf("%d\n",array[counter]);
		counter++;
	}
}
 
int main (int argc, char *argv[]){
	int array[] = {2929393,1,23239,-66,15,4,3,0,112,45,3,1000,19};
	int arraySize = sizeof(array)/sizeof(array[0]);
	int *firstElement = &array[0];
	int *lastElement = firstElement + arraySize;
	printf("-------------------------------------------------\n");
	printf("Elements of the array:\n");
	printf("-------------------------------------------------\n");
	printArray(array,arraySize);
	printf("-------------------------------------------------\n");
	sortArray(firstElement,lastElement);
	printf("Elements sorted:\n");
	printf("-------------------------------------------------\n");
	printArray(array,arraySize);
	printf("-------------------------------------------------\n");
}

A better program should ask the user to input the array elements, and a better algorithm should not scan every array element n times, where n is the number of the elements.
But I wrote it just for fun and for learning C pointers. I will learn to do better in the Data Structures and Algorithms course in the next semester ;)

3 Comments

Post a Comment

Your email is never shared. Required fields are marked *