The program is supposed to take a file, say data.dat, filled with a list of up to 320 words all less than or equal to 29 characters (30 with the null character) and add each of those words to a global array. Then I want to sort that list alphabetically with a bubble sort. I did so with the following function in its own file sort.c
#include "set.h"
#include "sortAndSearch.h"
#include <stdio.h>
#include <ctype.h>
#include <string.h>
void bubbleSort(char A[][30], int num) {
int i, j;
char temp[30];
for(i = 0; i < num; i++)
for(j = 0; j < num-1; j++)
if(strcmp(A[i], A[i+1]) > 0){
//swap the two array elements
strcpy(temp, A[j]);
strcpy(A[j], A[j+1]);
strcpy(A[j+1], temp);
}
}
I need a set of unsigned ints
unsigned int Set[10];
to act as an index for the names array. So each unsigned int has 32 bits and there are 10 unsigned ints for a total of 320 bits and each bit will reference a word. I am unsure how to approach this part.
The end goal is to create functions to manipulate the sets. I feel like I can attack that myself if I can get the sorting and index down, as I’ve done something similar but without using character arrays. The contents of the header file set.h that defines the functions to be used follows
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
// defining new type(s)
typedef unsigned int Set[10];
// declaring global variable(s)
extern char names[320][30];
extern void setUnion(Set set1, Set set2, Set result);
extern void setIntersection(Set set1, Set set2, Set result);
extern void clearSet(Set set);
extern void add2Set(Set set, int value);
extern void deleteFromSet(Set set, int value);
extern int isMember(Set set, int element);
extern void printSet(Set);
extern int nameIsMember(Set set, char *);
extern void addName2Set(Set set, char *);
extern void deleteNameFromSet(Set set, char *);
And here are the contents of the header file sortAndSearch.h
void bubbleSort(char A[][30], int num);
int binarySearch(char A[][30], char *, int, int );
Your bubble sort is in fact not a bubble sort. It only makes a single pass over the array. You need to repeatedly pass over the array until you make a pass that does not result in a swap. At that point you know that your array is ordered.
My preferred bubble sort implementation has an outer
doloop. The inner loop is just as you currently have. The outer loop terminates when the latest inner loop execution failed to swap any items.Of course, I’d recommend using a better sorting algorithm in the long run, but this is probably a homework assignment.