Fun

A couple of easy sort algorithms for you. Look ma, no array subscripts! C is the shit, kiddies!


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

#define ELEMENTS 10
#define ARRAY_ELEMENT_COUNT(array) (sizeof(array)/sizeof(array[0]))

//type-independent malloc
void *MyMalloc(size_t size)
{
void *vp;

if ((vp = malloc(size)) == NULL)
{
fputs("Cannot allocate memory for malloc.n",stderr);
exit(EXIT_FAILURE);
}

return(vp);
}

//swap void pointers
void SwapElements(void *pa,void *pb,size_t size)
{
//temp void pointer to hold an element to swap
void *tmp = MyMalloc(size);

//use memcpy to perform the swaps
memcpy(tmp,pa,size);
memcpy(pa,pb,size);
memcpy(pb,tmp,size);

free(tmp);
}

//bubble sort implementation, fancy-style.
void BubbleSort(float *first,size_t size)
{
float *current_offset,*current,*last = &first[size - 1];
int flag_swap;

do
{
for (flag_swap=0,current = first; current {
//set a pointer to pointer to current element of array
current_offset = current;

//increment the temp pointer
current_offset++;

//compare current element and current[1]
if (*current > *current_offset)
{
//cast to void pointers and swap
SwapElements(current,current_offset,sizeof(float));
flag_swap = 1;
}

}
}
while(flag_swap);
}

//just for fun
void ShuttleSort(float *first,size_t size)
{
float *current_offset,*current,*back,*last = &first[size - 1];

for (current = first; current {
current_offset = current;
current_offset++;

if (*current > *current_offset)
SwapElements(current,current_offset,sizeof(float));

for (back = current; back > first; --back)
{
current_offset = back;
current_offset--;

if (*back SwapElements(back,current_offset,sizeof(float));
else
break;
}
}
}

int main()
{
int i;
float arrToSort[ELEMENTS];

for (i = 0;i {
puts("Input a floating point number:");
scanf("%f",&arrToSort[i]);
}

//BubbleSort(arrToSort,ARRAY_ELEMENT_COUNT(arrToSort));
ShuttleSort(arrToSort,ARRAY_ELEMENT_COUNT(arrToSort));

puts("------------------------");
puts("Output of sorted array:");

for (i = 0;i printf("%fn",arrToSort[i]);

return(EXIT_SUCCESS);
}