Tuesday, July 28, 2009

Guys i need c program for Bubble Sort on the randomly generated numbers.?

There is a text file which has 1000 random numbers.I have to sort it using bubble sort and output should go to an output file (text format) and contain at least the algorithm name, the time for the sorting to be completed (in seconds to at least 4 decimal places), the number of “swaps” performed and the sorted list. Pls help me out

Guys i need c program for Bubble Sort on the randomly generated numbers.?
#include %26lt;stdio.h%26gt;


#include %26lt;stdlib.h%26gt;


#include %26lt;time.h%26gt;





unsigned int bubble_sort(unsigned int *array, size_t size) {


unsigned int swapped = 0, progress;


size_t n = size, i;





do {


progress = 0;


n -= 1;


for (i = 0; i %26lt; n; ++i) {


if (array[i] %26gt; array[i + 1]) {


unsigned int temp = array[i];


array[i] = array[i+1];


array[i+1] = temp;


++swapped;


progress = 1;


}


}


} while (progress);


return swapped;


}





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


FILE *fin, *fout;


unsigned int *array, swaps;


size_t size, i;


time_t start, end;





if (argc != 4) {


printf("Syntax: %s fileName n fileOut\n", argv[0]);


printf(" where fileName is the file containing the numbers\n");


printf(" n is the number of available integers\n");


printf(" fileOut is the file with sorted output numbers\n");


printf("\n");


return -1;


}





fin = fopen(argv[1], "r");


if (fin == NULL) {


printf("Couldn't open %s\n", argv[1]);


return -1;


}





fout = fopen(argv[3], "w");


if (fout == NULL) {


printf("Couldn't open %s\n", argv[3]);


printf -1;


}





// Read the numbers


size = atoi(argv[2]);


array = malloc(size * sizeof(unsigned int));


if (array == 0) {


printf("Not enough memory available.\n");


return -1;


}





for (i = 0; i %26lt; size; ++i) {


fscanf(fin, "%d", %26amp;array[i]);


}





// Sort the numbers


time(%26amp;start);


swaps = bubble_sort(array, size);


time(%26amp;end);





// Now outputs the file


fprintf(fout, "Bubble Sort\n");


fprintf(fout, "Time taken = %f seconds\n", difftime(end, start));


fprintf(fout, "Swaps = %d\n", swaps);


fprintf(fout, "\n");





for (i = 0; i %26lt; size; ++i) {


fprintf(fout, "%d\n", array[i]);


}





free(array);


fclose(fin);


fclose(fout);





return 0;


}
Reply:Well simply open the file using text access (or binary as required), then scan and input the data into an array (or allocate memory using malloc to an integer / long pointer).





Then, perform a bubble sort on this array. Keep a counter to keep track of the number of swaps (increment this by 1 every time a swap occurs in your sort method). Now all done.





Create the text file and write the sort name (fprintf), and the value of the counter followed by the values in the sorted array.


No comments:

Post a Comment