HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Comparing three O(n^2) search algorithms in C

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threecomparingsearchalgorithms

Problem

I'm currently taking Harvard's CS50 course via EdEx.org, and we're learning about sorting algorithms. More specifically, we're studying bubble, insertion, selection, and merge sorts.

Just for kicks and giggles, I went ahead and decided to write a program that compares all three. Basically, what it does is takes arrays of varying lengths, fills them with ascending values, then runs through every possible permutation of that array and has the different algorithms sort it. It then outputs the minimum, maximum, and average number of operations used for each algorithm in a .csv file so I can analyze them and make charts and whatnot.

Am I going about counting the number of operations required in each algorithm correctly?

```
#include
#include
#include
#include
#include
#include

struct result
{
int min;
int max;
unsigned long long total;
};

struct trial
{
int length;
struct result bubble;
struct result insertion;
struct result selection;
};

// prototypes
void run_trials(int start, int end, FILE bubble, FILE selection, FILE *insertion);

// Array functions
void swap(int arr[], int i, int j);
void fill(int arr[], int max);
void copy(int arr1[], int arr2[], int len);

// Sorting algorithms
int bubble(int arr[], int n);
int insertion(int arr[], int n);
int selection(int arr[], int n);

// Result handling
void prep_trial(struct trial *t, int i);
void prep_result(struct result *r);
void prep_file(FILE *fp);
void update_result(struct result *r, int operations);
void update_file(struct result r, int len, int count, FILE *fp);

int main(void)
{
FILE *bub;
FILE *sel;
FILE *ins;

// Open the file pointers
bub = fopen("bubble.csv", "w");
sel = fopen("selection.csv", "w");
ins = fopen("insertion.csv", "w");

// Check for errors
if (bub == NULL
|| sel == NULL
|| ins == NULL) {
printf("Unable to initialize one or more files. Exiting\n");
return 1;
}

// Add the top rows of each c

Solution

Permutations

You are attempting to generate every permutation of the array, but you aren't actually doing that. You are only generating \$n^2\$ permutations instead of \$n!\$ permutations. You could use something like Heap's algorithm if you really wanted to generate every permutation (but be careful, it could make your program run a very long time).

Probably better would be to generate random permutations rather than all permutations, to keep the runtime reasonable.

const keyword

As I was reading through your code I noticed that your sorting functions make a copy of the array passed in so that you don't modify the original. Your functions should mark unmodified arguments with const. It doesn't change your program behavior but it's a good habit to develop.

Context

StackExchange Code Review Q#101025, answer score: 4

Revisions (0)

No revisions yet.