Linear Sort Algorithm
A simple linear (bubble-style) sort for an array of C strings, with a pass function that reports how many swaps it made.
The most straightforward way to sort a list of strings in C: one pass (LinearSortEx) walks the array swapping any out-of-order adjacent pair and returns the number of swaps, and the outer LinearSort repeats passes until a full pass makes zero moves. It is O(n²) - fine for small lists, teaching material, or places where you want dead-simple code over speed. The driver sorts 230 names and prints the total swap count plus the final order.
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Windows.H>
#include <Stdio.H>
#include <StdLib.H>
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#define ELEMENTS 230
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int LinearSortEx(char **sArray, int iElements)
{
char *sTemp = NULL;
int iItemsMoved = 0;
for(int iElement = 0; iElement < iElements; iElement++)
{
if(strcmp(sArray[iElement], sArray[iElement + 1] ) > 0)
{
sTemp = sArray[iElement];
sArray[iElement] = sArray[iElement + 1];
sArray[iElement + 1] = sTemp;
iItemsMoved++;
}
}
return iItemsMoved;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
int LinearSort(char **sArray, int iElements)
{
int iTotalMoved = 0;
int iMoved = 0;
while((iMoved = LinearSortEx(sArray, iElements)) > 0)
{
iTotalMoved += iMoved;
}
return iTotalMoved;
}
Note it only swaps pointers, so it works on any array of string pointers regardless of where the text lives. Two quirks worth knowing before reusing: the comparison is case-sensitive (strcmp), so uppercase entries sort ahead of lowercase ones, and the inner loop runs to iElements inclusive, so the array needs one extra sentinel slot past the last real element (the driver declares ELEMENTS + 1).