I have written a program to measure execution time of quick sort and am using Code Blocks to compile and run it. When I input random set of numbers my program runs well for any size of data. But when I try to input ascending/descending sorted set of numbers, my program terminates for large data set (>35000) saying program stopped working.
This same code runs well on linux. But on linux I am not able to measure time using QueryPerformanceCounter(). So I have to use Code Blocks on windows.
#include<stdio.h>
#include<windows.h>
double PCFreq = 0.0;
__int64 CounterStart = 0;
void StartCounter()
{
LARGE_INTEGER li;
if(!QueryPerformanceFrequency(&li))
printf("QueryPerformanceFrequency failed!\n");
PCFreq = (double)li.QuadPart;
QueryPerformanceCounter(&li);
CounterStart = li.QuadPart;
}
double GetCounter()
{
LARGE_INTEGER li;
QueryPerformanceCounter(&li);
return (double)(li.QuadPart-CounterStart)/PCFreq;
}
int part(int a[],int low,int high)
{
int pivot,i,j,temp;
pivot=low;
i=low+1;
j=high;
while(i<=j)
{
while(a[i]<=a[pivot])
i++;
while(a[j]>a[pivot])
j--;
if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[j];
a[j]=a[pivot];
a[pivot]=temp;
return j;
}
void QuickSort(int a[],int first,int last)
{
int q;
if(first<last)
{
q=part(a,first,last);
QuickSort(a,first,q-1);
QuickSort(a,q+1,last);
}
}
int main()
{
int n,a[100000],i;
printf("Enter the size of array:");
scanf("%d",&n);
for(i=0;i<n;i++)
//a[i]=rand()%100000; //average case (random data)
a[i]=i; //ascending sorted input
//a[i]=n-1-i; //descending sorted input
/*
printf("The UNsorted array is:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n\n");
*/
StartCounter();
QuickSort(a,0,n-1);
printf("Sorting time %lf micro seconds\n",GetCounter()*1000000.0);
/*
printf("\nThe sorted array is:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
*/
return 0;
}
I am getting following error
If I use clock(3) (sufficient resolution for a quick test) on Linux it works up to and including the fixed limit of 100000. To avoid that fixed limit I used malloc() to reserve the memory dynamically in the following sketch (doesn't make a difference in the outcome, I just wanted to put it on the heap instead of the stack)
#include <time.h>
#include <stdlib.h>
// ALL CHECKS OMMITTED!
int main()
{
int n,*a,i;
clock_t start, stop;
printf("Enter the size of array:");
scanf("%d",&n);
a = malloc(sizeof(int) * n);
for(i=0;i<n;i++)
//a[i]=rand()%100000; //average case (random data)
a[i]=i; //ascending sorted input
//a[i]=n-1-i; //descending sorted input
/*
printf("The UNsorted array is:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n\n");
*/
start = clock();
QuickSort(a,0,n-1);
stop = clock();
printf("Sorting time %f seconds\n", (double)(stop- start)/CLOCKS_PER_SEC);
/*
printf("\nThe sorted array is:\n");
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
*/
free(a);
return 0;
}
Ascending array entries: 11 seconds for 100,000 entries and for a million…a segfaulta at
QuickSort (a=0x7ffff7ee3010, first=174677, last=199999)
(repeatable)
I think the recursion is just a wee bit too deep (stack size here: 8 megs which goes accord for 180,00 calls with two ints and a pointer and some overhead).
So: nothing actually wrong here.
EDIT
To show that it is indeed the stack lets increase it:
#include <time.h>
#include <stdlib.h>
#include <sys/resource.h>
// ALL CHECKS OMMITTED!
int main()
{
int n, *a, i;
clock_t start, stop;
// 256 MB
const rlim_t bigger_stack = 256L * 1024L * 1024L;
struct rlimit rlim;
int ret_set, ret_get;
ret_get = getrlimit(RLIMIT_STACK, &rlim);
fprintf(stderr, "get %d %d %d\n", ret_get, (int) rlim.rlim_max,
(int) bigger_stack);
if (ret_get == 0) {
if (rlim.rlim_cur < bigger_stack) {
rlim.rlim_cur = bigger_stack;
ret_set = setrlimit(RLIMIT_STACK, &rlim);
if (ret_set != 0) {
fprintf(stderr, "getrlimit %d, setrlimit %d\n", ret_get, ret_set);
}
}
}
printf("Enter the size of array:");
scanf("%d", &n);
a = malloc(sizeof(int) * n);
for (i = 0; i < n; i++)
//a[i]=rand()%100000; //average case (random data)
a[i] = i; //ascending sorted input
//a[i]=n-1-i; //descending sorted input
/*
* printf("The UNsorted array is:\n");
* for(i=0;i<n;i++)
* printf("%d ",a[i]);
* printf("\n\n");
*/
start = clock();
QuickSort(a, 0, n - 1);
stop = clock();
printf("Sorting time %f seconds\n", (double) (stop - start) / CLOCKS_PER_SEC);
/*
* printf("\nThe sorted array is:\n");
* for(i=0;i<n;i++)
* printf("%d ",a[i]);
* printf("\n");
*/
free(a);
return 0;
}
Checked with 200,000 elements: works in ca. 47 seconds.
Related
I need help fixing my median calculations. When I try to print the median value it prints wrong. Here is my code. I need help to determine the median value via the sorted numbers. The program reads in 10 integers from an array and prints out minimum, maximum and average values.
#include <stdio.h>
#include <stdlib.h>
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
// Maximum
int maximum(int values[]) {
int Maximum = values[0];
for (int i = 0; i < 10; ++i) {
if (values[i] > Maximum)
{
Maximum = values[i];
}
}
return Maximum;
}
// Minimum
int minimum(int values[]){
int Minimum= values[0];
for(int i = 0; i < 10; ++i) {
if (values[i] < Minimum)
{
Minimum = values[i];
}
}
return Minimum;
}
int main() {
printf("Hello, World!\n");
//
int a[10],i,sum=0;
printf("enter array\n");
for(i=0;i<10;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
int max = maximum(a);
int mini = minimum(a);
float avg =(float ) sum/10;
qsort(a, 10, sizeof(int), cmpfunc);
int medianNumber= i/2;
int median=a[medianNumber];
printf("Sum: %d\n",sum);
printf("Maximum: %d\n" , max);
printf("Minimum: %d\n", mini);
printf("Average: %g\n" , avg);
//printf("Median: %2.2f\n", median);
printf("Median:= %d\n" ,a[i]);
printf("Sorted: ");
for( int n = 0; n < 10; n++ ) {
printf("%i ", a[n]);
}
return (0);
}
Issues:
Per the definition of median
This approach:
int medianNumber= i/2;
int median=a[medianNumber];
Will only work for an odd set of numbers.
Use the following to cover both odd and even sets:
//if even number of elements, median is average of two middle values
int medianNumber = 0;
float median = 0;
if(i%2 == 0)//even number of elements
{
medianNumber= (i/2)-1;//zero based indices
median=(a[medianNumber]+a[medianNumber+1])/2.0;
}
else // odd number of elements
{
medianNumber= (i/2);//zero based indices
median=a[medianNumber];
}
Also, when this for loop exits,
for(i=0;i<10;i++)
{
...
}
the value for i will be 10 causing an array index out-of-bounds error here:
//printf("Median: %2.2f\n", median);
printf("Median:= %d\n" ,a[i]);
^
I would assume that you meant to use the index value a[medianNumber], or more appropriate, use the value you have determined for median
printf("Median:= %d\n" ,median);
The following full code includes some additional fixes, and a #define ELEMENTS statement to make testing even and odd number of elements a little easier to edit.
#define ELEMENTS 9 //test for odd and even values
int main(void) {
printf("Hello, World!\n");
//
int a[10],i,sum=0;
printf("enter array\n");
for(i=0;i<ELEMENTS;i++)
{
scanf("%d",&a[i]);
sum=sum+a[i];
}
int max = maximum(a);
int mini = minimum(a);
float avg =(float ) sum/ELEMENTS;
qsort(a, ELEMENTS, sizeof(int), cmpfunc);
//if even number of elements, median is average of two middle values
int medianNumber = 0;
float median = 0;
if(i%2 == 0)//even number of elements
{
medianNumber= (i/2)-1;//zero based indices
median=(a[medianNumber]+a[medianNumber+1])/2.0;
}
else // odd number of elements
{
medianNumber= (i/2);//zero based indices
median=a[medianNumber];
}
printf("Sum: %d\n",sum);
printf("Maximum: %d\n" , max);
printf("Minimum: %d\n", mini);
printf("Average: %g\n" , avg);
printf("Median:= %0.3f\n" ,median);
printf("Sorted: ");
for( int n = 0; n < ELEMENTS; n++ ) {
printf("%i ", a[n]);
}
return 0;
}
The problem is in this line:
printf("Median:= %d\n" ,a[i]);
You are printing element the element designated by i in the array, but i is just a loop counter.
After you run your loop, i = 10.
But you are calculating the correct array position for median here:
int medianNumber= i/2;
int median=a[medianNumber];
So you should be printing the element of the array designated by medianNumber, like this:
printf("Median:= %d\n" ,a[medianNumber]);
If you want to take the average for values a[4] and a[5] to discover the median, then you need to do:
float median = ((float)a[4] + (float)a[5]) / 2;
and then your print statement needs to look like this:
printf("Median:= %g\n" , median);
When printing, %f will print as many decimals as you tell it to print every time, so %2.2f will always print two decimal places. %g will only print decimals if they are not zeros, and will omit trailing zeros.
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define LIMIT 30000
void CreateArray(int *p, int N) {
int i;
p = (int *)malloc(N * sizeof(int));
srand((long)210);
for (i = 0; i < N; i++)
*(p + i) = rand() % LIMIT;
for (i = 0; i < N; i++)
printf("%d ", p[i]);
}
void Search(int *p, int N, int key) {
int comparisons = 0, success_search = 0;
int i;
clock_t start, end;
double elapsed;
start = clock();
for (i = 0; i < N; i++) {
if (key == p[i]) {
comparisons++;
success_search++;
printf("\nFound!");
break;
} else {
comparisons++;
printf("\nNot found!");
}
}
end = clock();
elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("\nTotal comparisons: %d \n", comparisons);
printf("Time elapsed: %f \n", elapsed);
printf("Successful comparisons: %d \n\n", success_search);
}
int main() {
int N, i, p, key;
key = 1;
CreateArray(&p, N = 7);
Search(&p, N, key);
}
I'm trying to create a pseudo-random array and then try to search for a specific number in it and keep track of the total comparisons made and the total time needed to complete the search. I have manually inserted a number that is not in the array and it keeps saying that the number was found after 3 comparisons. Also the time elapsed always appears to be zero. I can't figure out what's wrong.
Make the following changes.
1) You need to allocate array and pass it to different functions. So "n" should be a pointer.
int *n = NULL;
2) You want CreateArray() to allocate memory and pass the pointer.
void CreateArray (int **p, int N)
3) You have to pass pointer to Search(). So call from main() becomes
Search(p, N, key);
I think it should work fine as expected now.
For time elapsed, you refer to Weather Vane's comment in your question.
There are multiple problems in your code:
CreateArray should return the pointer to the allocated space. Passing it a pointer to a local int in main() makes no sense.
you should test for malloc potential failure.
Search should get the pointer to the allocated array, not the address of a local int.
Search should print the Not found message just once at the end of the scan phase.
If you want to count the number of successful comparisons, you should not break from the loop when you find the first one, but then the total number of comparisons is N.
for better timing accuracy, you should avoid using printf inside the timed fragment.
you should free the memory before exiting the program.
Here is a corrected version:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define LIMIT 30000
void CreateArray(int N) {
int i;
int *p = (int *)malloc(N * sizeof(int));
if (p != NULL) {
srand((long)210);
for (i = 0; i < N; i++)
*(p + i) = rand() % LIMIT;
for (i = 0; i < N; i++)
printf("%d ", p[i]);
}
return p;
}
void Search(int *p, int N, int key) {
int comparisons = 0, success_search = 0;
int i;
clock_t start, end;
double elapsed;
start = clock();
for (i = 0; i < N; i++) {
comparisons++;
if (key == p[i])
success_search++;
}
end = clock();
elapsed = ((double)(end - start)) / CLOCKS_PER_SEC;
if (success_search)
printf("Found!\n");
else
printf("Not found!\n");
printf("Total comparisons: %d\n", comparisons);
printf("Successful comparisons: %d\n\n", success_search);
printf("Time elapsed: %f\n", elapsed);
}
int main() {
int N, i, key;
int *p;
key = 1;
N = 7;
p = CreateArray(N);
if (p == NULL) {
fprintf(stderr, "cannot allocate memory for %d elements\n", N);
return 1;
}
Search(p, N, key);
free(p);
return 0;
}
This is the code I have come up so far. This may not be the best way to scan in an array separated by spaces. So what I need to do is sort the in putted array into ascending order and print it. Hopefully somebody can help me out!
int main()
char vect1[25];
char *num1;
//First Vector
printf("Enter first Vector seperated by spaces\n");
fgets(vect1, 25, stdin);
printf("The unsorted vector is:\n");
double v1[25];
int count1=0;
num1 = strtok(vect1, " ");
while (num1 != NULL)
{
sscanf(num1, "%lf", &v1[count1]);
printf("%.2f\n", v1[count1]);
num1 = strtok(NULL, " ");
count1++;
}
printf("Size of Array= %d\n\n", count1);
Output is:
Enter first Vector separated by spaces
User inputs vector (eg. 5 4 9 3 8 2 1)
5
4
9
3
8
2
1
size of array= 7
Bubble sort, easy and fast enough for small arrays.
int main()
char vect1[25];
char *num1;
char swap;
//First Vector
printf("Enter first Vector seperated by spaces\n");
fgets(vect1, 25, stdin);
printf("The unsorted vector is:\n");
double v1[25];
int count1=0;
num1 = strtok(vect1, " ");
while (num1 != NULL)
{
sscanf(num1, "%lf", &v1[count1]);
printf("%.2f\n", v1[count1]);
num1 = strtok(NULL, " ");
count1++;
}
for (int c = 0 ; c < ( count1 - 1 ); c++)
{
for (int d = 0 ; d < - c - 1; d++)
{
if (array[d] > array[d+1]) /* For decreasing order use < */
{
swap = array[d];
array[d] = array[d+1];
array[d+1] = swap;
}
}
}
Here is your code with the added quicksort() function I wrote that will return a sorted array for you. I just chose quicksort because I like it, but any sorting algorithm could be used.
I've added all pertinent functions to get quicksort working, and I've added all their function prototypes above main(). I've also added a print_array function that prints the elements in the array in the same format that you were printing them.
Also, I added the line
#define VECSIZE 25
after the include statements at the top of the file. You were using the value 25 a lot as a constant, so if you ever wanted to change the value to another number, you would have had to change it in many different spots. Now, if you want to change the size of the vector, all you have to do is change the value of VECSIZE.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define VECSIZE 25
/* function prototypes */
void quicksort(double *vector, int low, int high);
int partition(double *vector, int low, int high);
void swap(double *array, int i, int j);
void print_array(double *array, int size);
int main() {
char vect1[VECSIZE];
char *num1;
//First Vector
printf("Enter first Vector seperated by spaces\n");
fgets(vect1, VECSIZE, stdin);
double v1[VECSIZE];
int count1=0;
num1 = strtok(vect1, " ");
while (num1 != NULL)
{
sscanf(num1, "%lf", &v1[count1]);
num1 = strtok(NULL, " ");
count1++;
}
printf("The unsorted vector is: \n");
print_array(v1, count1);
printf("Size of Array= %d\n\n", count1);
quicksort(v1, 0, count1-1); // count1-1 is the index of the last element in the array
printf("The sorted vector is: \n");
print_array(v1, count1);
}
void print_array(double *array, int size){
int i;
for (i = 0; i < size; i++)
printf("%.2f\n", array[i]);
printf("\n");
}
/*
x and y are indices into the array, and the values
at those indexs will be swapped
*/
void swap(double *array, int x, int y) {
int placeholder = array[x];
array[x] = array[y];
array[y] = placeholder;
}
/*
Sorts a single element in the array and returns its
sorted index.
*/
int partition(double *array, int low, int high) {
int i = low-1;
int j = low;
double pivot = array[high];
for (j; j < high; j++) {
if (array[j] <= pivot) {
i++;
swap(array, i, j);
}
}
i++;
swap(array, i, high);
return i;
}
/*
recursively sorts an array by sorting the values in the
array that are left of 'mid' and then sorting the values
that are greater than 'mid'. The brains of this sorting
algorithm is in the partition function.
*/
void quicksort(double *array, int low, int high) {
int mid;
if (low < high) {
mid = partition(array, low, high);
quicksort(array, low, mid-1);
quicksort(array, mid+1, high);
}
}
I wrote some C code to analyze the number of comparisons and runtime of building a heap and running heapsort. However, I'm not sure if the output of my code makes sense. Heapsort should perform at O(n log n), but the number of comparisons I'm seeing doesn't seem to be very close to that. For example, for an input of size n = 100, I'm seeing ~200 comparisons to build the heap and ~800 comparisons in heap sort. Am I just analyzing the data wrong, or is there something wrong with the way I'm collecting comparisons in my code?
I can provide a link to github if it would make a difference for anyone.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
void bottom_up_heap_sort(int*, int);
void heap_sort(int*, int);
void sift_up(int*, int);
void sift_down(int*, int);
void build_max_heap(int*, int);
void bottom_up_build_max_heap(int*, int);
void randomize_in_place(int*, int);
int* generate_array(int);
void swap(int*, int*);
int cmp(int, int);
void print_array(int*, int);
int heapsize;
unsigned long comparison_counter;
clock_t begin, end;
double time_spent;
int main() {
int k, N;
int* A;
int* B;
int i;
printf("Testing Sift_Down Heap Sort\n");
for(k = 2; k <= 5; k++) {
comparison_counter = 0;
N = (int)pow((double)10, k);
begin = clock();
A = generate_array(N);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time Spent Generating Array: %f\n", time_spent);
// print the first unsorted array
//printf("Unsorted Array:\n");
//print_array(A, N);
begin = clock();
// call heap_sort on the first unsorted array
heap_sort(A, N);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
// show that the array is now sorted
//printf("Sorted array: \n");
//print_array(A, N);
printf("Done with k = %d\n", k);
printf("Comparisons for Heap Sort: %lu\n", comparison_counter);
printf("Time Spent on Heap Sort: %f\n", time_spent);
printf("\n");
}
printf("----------------------------------\n");
printf("Testing Sift_Up Heap Sort\n");
for(k = 2; k <= 5; k++) {
comparison_counter = 0;
N = (int)pow((double)10, k);
begin = clock();
B = generate_array(N);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
printf("Time Spent Generating Array: %f\n", time_spent);
// print the unsorted array
//printf("Unsorted Array:\n");
//print_array(B, N);
begin = clock();
// call heap_sort on the unsorted array
bottom_up_heap_sort(B, N);
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
// show that the array is now sorted
//printf("Sorted array: \n");
//print_array(B, N);
printf("Done with k = %d\n", k);
printf("Comparisons for Heap Sort: %lu\n", comparison_counter);
printf("Time Spent on Heap Sort: %f\n", time_spent);
printf("\n");
}
printf("----------------------------------\n");
return 0;
}
void bottom_up_heap_sort(int* arr, int len) {
int i;
// build a max heap from the bottom up using sift up
bottom_up_build_max_heap(arr, len);
printf("Comparisons for heap construction: %lu\n", comparison_counter);
comparison_counter = 0;
for(i = len-1; i >= 0; i--) {
// swap the last leaf and the root
swap(&arr[i], &arr[0]);
// remove the already sorted values
len--;
// repair the heap
bottom_up_build_max_heap(arr, len);
}
}
void heap_sort(int* arr, int len) {
int i;
// build a max heap from the array
build_max_heap(arr, len);
printf("Comparisons for heap construction: %lu\n", comparison_counter);
comparison_counter = 0;
for(i = len-1; i >= 1; i--) {
swap(&arr[0], &arr[i]); // move arr[0] to its sorted place
// remove the already sorted values
heapsize--;
sift_down(arr, 0); // repair the heap
}
}
void sift_down(int* arr, int i) {
int c = 2*i+1;
int largest;
if(c >= heapsize) return;
// locate largest child of i
if((c+1 < heapsize) && cmp(arr[c+1], arr[c]) > 0) {
c++;
}
// if child is larger than i, swap them
if(cmp(arr[c], arr[i]) > 0) {
swap(&arr[c], &arr[i]);
sift_down(arr, c);
}
}
void sift_up(int* arr, int i) {
if(i == 0) return; // at the root
// if the current node is larger than its parent, swap them
if(cmp(arr[i], arr[(i-1)/2]) > 0) {
swap(&arr[i], &arr[(i-1)/2]);
// sift up to repair the heap
sift_up(arr, (i-1)/2);
}
}
void bottom_up_build_max_heap(int* arr, int len) {
int i;
for(i = 0; i < len; i++) {
sift_up(arr, i);
}
}
void build_max_heap(int* arr, int len) {
heapsize = len;
int i;
for(i = len/2; i >= 0; i--) {
// invariant: arr[k], i < k <= n are roots of proper heaps
sift_down(arr, i);
}
}
void randomize_in_place(int* arr, int n) {
int j, k;
double val;
time_t t;
// init the random number generator
srand((unsigned)time(&t));
// randomization code from class notes
for(j = 0; j < n-1; j++) {
val = ((double)random()) / 0x7FFFFFFF;
k = j + val*(n-j);
swap(&arr[k], &arr[j]);
}
}
// this function is responsible for creating and populating an array
// of size k, and randomizing the locations of its elements
int* generate_array(int k) {
int* arr = (int*) malloc(sizeof(int)*k-1);
int i, j, x, N;
double val;
time_t t;
// init the random number generator
srand((unsigned)time(&t));
// fill the array with values from 1..N
for(i = 0; i <= k-1; i++) {
arr[i] = i+1;
}
N = (int)pow((double)10, 5);
// randomize the elements of the array for 10^5 iterations
for(i = 0; i < N; i++) {
randomize_in_place(arr, k);
}
return arr;
}
// swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}
int cmp(int a, int b) {
comparison_counter++;
if(a > b) return 1;
else if(a < b) return -1;
else return 0;
}
// print out an array by iterating through
void print_array(int* arr, int size) {
int i;
for(i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
}
O(n log n) (or in general O(f(x))) does not give you any idea about the expected value at a single point.
That's because big-O notation ignores constant factors. In other words, all of n * log(n), 0.000001 * n * log(n) and 1000000 * n * log(n) are in O(n log n). So the result for a particular value of n is completely undetermined.
What you can deduce from big-O notation is the effect of modify the control variable. If a function involves O(n) operations, then it is expected that doubling n will double the number of operations. If a function involves O(n2) operations, then it is expected that doubling n will quadruple the number of operations. And so on.
The actual number for such small values of n doesn't really matter, as the constant factors are omitted in the complexity. What matters is the growth of your algorithm, measuring for increasingly larger values of n, and plotting them should give roughly the same graph as your theoretical complexity.
I tried your code for a couple of n, and the increase in complexity was approximately O(n logn )
I'm trying to write a program that calculates the run-time of a bubble sort vs an insertion sort. It takes in two inputs, number of elements and elements, and calculates their run-time. This is what I have so far, but it is printing the same time for both sorters.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int bubblesort(int a[], int n);
int insertionsort(int a[], int n);
int main()
{
int s,temp,i,j,comparisons,a[20];
float function_time;
clock_t start;
clock_t end;
printf("Enter total numbers of elements: ");
scanf("%d",&s);
printf("Enter %d elements: ",s);
for(i=0;i<s;i++)
scanf("%d",&a[i]);
//Bubble sorting algorithm
for(i=s-2;i>=0;i--)
{
for(j=0;j<=i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
for(i=0;i<s;i++)
a[i]= rand()%10000;
start = clock();
comparisons= bubblesort(a, s);
end = clock();
function_time = (float)(end)/(CLOCKS_PER_SEC); // Time in seconds
printf("\nTime for Bubble Sort is %f microseconds\n ", function_time);
// Insertion sorting algorithm
for(i=1;i<s;i++)
{
temp=a[i];
j=i-1;
while((temp<a[j])&&(j>=0))
{
a[j+1]=a[j];
j=j-1;
}
a[j+1]=temp;
}
for(i=0;i<s;i++)
a[i]= rand()%10000;
start = clock();
comparisons= insertionsort(a, s);
end = clock();
function_time = (float)(end)/(CLOCKS_PER_SEC); // Time in seconds
printf("\nTime for Insertion Sort is %f microseconds\n ", function_time);
return 0;
}
int bubblesort(int a[], int n)
{
bool swapped = false;
int temp=0, counter=0;
for (int j = n-1; j>0; j--)
{
swapped = false;
for (int k = 0; k<j; k++)
{
counter++;
if (a[k+1] < a[k])
{
temp= a[k];
a[k] = a[k+1];
a[k+1]= temp;
swapped = true;
}
}
if (!swapped)
break;
}
return counter;
}
int insertionsort(int a[], int n)
{
bool swapped = false;
int temp=0, counter=0;
for (int i=1; i<=n; i++)
{
for (int s=i; s>0; s--)
{
counter++;
if (a[s]<a[s-1])
{
temp=a[s-1];
a[s-1]=a[s];
a[s]=temp;
swapped = true;
}
}
if (!swapped)
break;
}
return counter;
}
Firstly, the way you calculate the sorting time is wrong:
function_time = (float)(end)/(CLOCKS_PER_SEC);
It should be:
function_time = (float)(end-start)/(CLOCKS_PER_SEC);
Secondly, although bubble sort and insertion sort both have O(n square) complexity, time taken should have some difference, they cannot be the same. If the problem persists, you should check the output of clock() function, it may not work in your system.
Edit: I found that your code let user type in the elements manually. So I guess your array can only be relatively small. Sorting small-size array takes very little time so the difference is hard to notice. You should let the elements assigned randomly by code, so that you can generate large array for analysis.