Radeef sort – C code

// Please let me know better way to publish code in WordPress

 

// Radeef sort is useful in sorting an anthology of Ghazals, where the last word(s) of each couplet remain(s) same. Such word(s) is/are called Radeef

// Here is crude code of Radeef sort – sorting starting with last character, coming forward

// In essence, Radeef sort of an array of strings is “invert strings, sort, invert them again”

 

// Present program has many limitations. The goal is to just give an idea

// Most code here is copied from public domain – just Radeef sort idea remains original

 

// Example Input File:

/*

Geo
Duo
Jungle
Jingle
Support
By
Fantastic

*/

// after Radeef sort becomes

/*

Fantastic
Jingle
Jungle
Geo
Duo
Support
By

*/

 

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

#define MAX_LINE 80

FILE * Fopen (char *name, char *mode) {
FILE *fp;
fp = fopen(name, mode);
if ( fp == NULL ) {
fprintf( stderr, “%p\tCan’t open %s\n”, fp, mode);
exit (1);
}
return fp;
}

void strings_sort (int lineCount, char names[][MAX_LINE]) {
int i, j;
char word[MAX_LINE];

for(i=0;i< lineCount;i++) {
for(j=i+1;j< lineCount;j++){
if(strcmp(names[i],names[j])>0){
strcpy(word,names[i]);
strcpy(names[i],names[j]);
strcpy(names[j],word);
}
}
}
}

int main(int argc, char *argv[])
{

FILE *inFile, *outFile;
int lineCount;
int inputError;
char word [MAX_LINE];
int i,j;

if ( argc < 3 ) {
fprintf( stderr, “usage: radeefsort inputfile outputfile\n” );
system(“PAUSE”);
return (1);
}

// read a file containing strings and store it in an array of strings
// invert strings in that array of strings

inFile = Fopen (argv[1], “r”);

lineCount = 0;
while(inputError != EOF) {
inputError = fscanf(inFile, “%s\n”, word);
lineCount++;
}
fclose(inFile);
lineCount–;
// Above iterates lineCount++ after the EOF to allow for an array
// that matches the line numbers

char names[lineCount][MAX_LINE];

inFile = Fopen (argv[1], “r”);
for(i = 0; i < lineCount; i++) {
fscanf(inFile, “%s”, names[i]);
strcpy (names[i], strrev(names[i]));
}
fclose(inFile);

// sort this array of strings
strings_sort (lineCount, names);

// invert strings in that array of strings
// output that array of strings into a file
outFile = Fopen(argv[2], “w+”);

for(i = 0; i < lineCount; i++) {
fprintf (outFile, “%s\n”, strrev(names[i]));
}
fclose (outFile);
}

Advertisements

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