Hi,
I just recently joined and i need some help with one of my assignments. please can you have a look and try to help thank you.
task:
Write an efficient bubble sort function optimised so as not to check data that is guaranteed to be in the correct position (i.e. each pass is shorter than the previous one). It should include code (as the naivesort program below does) that counts the number of comparisons performed storing the result in a call by reference variable to pass the information back to the calling function. Your program should print out a copy of the array before and after sorting. Include a test function that tests the code for a series of data sets containing from 1 to 100 pieces of randomly generated data. Modify the program given below.
Code:
// Sort an array of integers using naive sort: multiple
// passes with smaller values gradually bubbling up to the
// top. It works by repeated comparison of pairs of values
// Count critical ops and save in a file for sorting array sizes up to 100
// For gcc compiler:
// gcc -std=c99 naivesort.c -o naivesort
// even harder options -ansi -pedantic
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void naive_sort (int array [], int arraySize, int * count);
void swap (int * v1, int * v2);
void fill_array (int array [], int arraySize);
void print_array(int array[], int sizeOfData);
const int RANGE = 200; // random data used in range 0-199
int main()
{
const int arraySize = 100;
int a[arraySize];
FILE *resultsFile;
// open the file for writing ("w")
resultsFile = fopen("nsort.dat", "w");
if (resultsFile != NULL) // file successfully opened
{
// seed the random number generator so it gives different
// random numbers each time
srand ( time (0) );
// Table headings
printf ("Found\t Data Size\t Comparisons Needed\n" );
//\t puts in a tab character, \n a new line
fprintf (resultsFile, "Data Size\t Comparisons Needed\n" );
// Generate table for data of different sizes
// giving number of comparisons each time
for (int datasize = 1; datasize <= arraySize; datasize = datasize + 1)
{
int count = 0; // number of comparisons this time
fill_array(a, datasize);
naive_sort (a, datasize, & count);
// print results in a table
printf("%d \t\t\t %d\n", datasize, count);
fprintf(resultsFile, "%d \t\t\t %d\n", datasize, count);
}
print_array(a, arraySize); // check final version at least was sorted
}
else
fprintf(resultsFile, "File not opened\n");
fclose(resultsFile); return 0;
}