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.
Related
Recently I am doing a school task that ask us to write a program to count the number of comparisons for bubble sort and insertion sort.
However, when I execute the program, it returns 2 same value for bubble sort and insertion sort.
Example:
Sorted!
Number of comparison for bubble sort: 559150
Number of comparison for insertion sort: 559150
Here is my program:
#include<stdio.h>
#include<time.h>
#define SIZE 1500
void swap(int *a,int *b) //swap function
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int bubblesort(int x[]) //Bubble sort
{
int i,j;
int count = 0;
for(i=0;i<SIZE-1;i++)
{
for(j=0;j<SIZE-i-1;j++)
{
if(x[j]>x[j+1])
{
swap(&x[j],&x[j+1]);
count = count + 1; //count comparison
}
}
}
return count;
}
int insertionsort(int x[]) //Insertion sort
{
int i,j,temp;
int count = 0;
for(i=1;i<SIZE;i++)
{
temp = x[i];
j = i-1;
while((j>=0)&&(x[j]>temp))
{
count = count + 1; //count comparison
x[j+1] = x[j];
j--;
}
x[j+1] = temp;
}
return count;
}
int main()
{
int i;
int b_array[SIZE];
int i_array[SIZE];
int b_count = 0;
int i_count = 0;
srand(time(NULL));
for(i=0;i<SIZE;i++) //Generate random number and assign it the the array
{
b_array[i] = rand()%SIZE;
i_array[i] = b_array[i];
}
b_count = bubblesort(b_array);
i_count = insertionsort(i_array);
printf("Sorted!\n");
printf("Number of comparison for bubble sort: %d\n",b_count);
printf("Number of comparison for insertion sort: %d",i_count);
return 0;
}
I want to know where the problem is? and how can I solve it?
Thanks a lot.
Number of comparisons - how many times program reach if statement.
In case of bubble sort - if(x[j]>x[j+1]).
In case of insertion sort - (x[j]>temp) in while loop. So you are counting number of swaps not comparisons.
int bubblesort(int x[])
{
int i,j;
int count = 0;
for(i=0;i<SIZE-1;i++)
{
for(j=0;j<SIZE-i-1;j++)
{
count++; //comparison. Increment "count" each time program reach "if"
if(x[j]>x[j+1])
{
swap(&x[j],&x[j+1]);
}
}
}
return count;
}
I don't see anything strange with this at all. They both have the same time complexity, which is O(n²). They also have O(n²) comparisons. Besides. If you analyze bubble sort and insertion sort (the variant without binary search, which is the one you're using) you'll find that they are VERY similar.
But when I look in your code, you do not count comparisons. You count swaps.
for(j=0;j<SIZE-i-1;j++) {
// Move it outside the comparison
count = count + 1; //count comparison
if(x[j]>x[j+1]) {
swap(&x[j],&x[j+1]);
}
}
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.
I have a project for my university. In this project I must make a program in C language for sorting a huge table (30000 integers) with some sorting methods like bubble,quick,straight insertion and straight selection. In the output should be the number of changes in every sorting method and the time that was needed to completed. I have two problems:
I cannot show the time that was needed
I must redirect the output to a file but I don't know how to make it.
Here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 300
int getUniqueNumber(int p[N],int i);
int StraightInsertion(int p[]);
int StraightSelection(int p[]);
int BubbleSort(int p[]);
int quicksort(int left, int right, int p[]);
int main(int argc, char *argv[])
{
FILE *f;
int c,p[N],p2[N];
int i,b;
int t0,t1,dt;
int s=0;
do{
for (i=0;i<N;i++)
p2[i]=getUniqueNumber(p2,i);
for(i=0;i<N;i++)
p[i]=p2[i];
printf("\nTable after sorts:\n");
printf("\n\n\n");
printf("straight selection %d\n",s+1);
time(&t0);
c=StraightSelection(p);
time(&t1);
dt=t1-t0;
printf("\n Number of changes: %d\n",c);
printf(" Processing time: %d\n",dt);
// straight insertion table
for(i=0;i<N;i++)
p[i]=p2[i];
printf("\n\n\n");
printf("straight isertion %d\n",s+1);
time(&t0);
c=StraightInsertion(p);
time(&t1);
printf("\n number of changes: %d",c);
dt=t1-t0;
printf(" Processing time = %f\n",dt);
// Bubble Sort table
for(i=0;i<N;i++)
p[i]=p2[i];
printf("\n\n\n");
printf("Bubble sort %d\n",s+1);
time(&t0);
c=BubbleSort(p);
time(&t1);
printf("\n Number of changes: %d\n",c);
dt=t1-t0;
printf(" Processing time = %f\n",dt);
// Quick Sort table
for(i=0;i<N;i++)
p[i]=p2[i];
printf("\n\n\n");
printf("Quick sort %d",s+1);
time(&t0);
c=quicksort(0,N-1,p);
time(&t1);
dt=t0-t1;
printf("\n Number of changes: %d\n",c);
printf(" Processing time = %f\n",dt);
s++;
}
while(s<20);
return 0;
}
int getUniqueNumber(int p[N],int i)
{
int x,j, found;
srand(time(NULL));
do
{
x = rand();
found = 0;
j = 0;
while (j<=i && found == 0)
{
if (p[j] == x)
found = 1;
else
j++;
}
}while (found == 1);
return x;
}
// STRAIGHT SELECTION
int StraightSelection(int p[])
{
int i,j,k,min=0,a[N];
int count=0;
for (i=0; i<N-1; i++)
{
k = i;
min = p[i];
for (j = i+1; j<N; j++)
{
if (p[j] < min)
{
k = j;
min = p[j];
count ++;
}
}
p[k] = p[i] ;
p[i] = min;
}
return count;
}
//Straight Insertion
int StraightInsertion(int p[])
{
int i,j,x;
int count=0;
for(i=1; i<N; i++)
{
x = p[i];
j = i -1;
while(x<p[j] && j>=0)
{
p[j+1] = p[j];
j = j-1;
count ++;
}
p[j+1] = x;
}
return count;
}
//Bubble Sort
int BubbleSort(int p[])
{
int i,j,temp;
int count;
for (i=1; i<N; i++)
for (j=N-1; j>=i; j--)
if (p[j-1] > p[j])
{
temp = p[j-1];
p[j-1] = p[j] ;
p[j] = temp ;
count ++;
}
return count;
}
//Quick Sort
int quicksort(int left, int right, int p[])
{
int i, j, mid, x, temp;
int count=0;
if (left < right)
{
i = left;
j = right;
mid = (left+right)/2;
x = p[mid];
while (i < j)
{
while (p[i] < x)
i++;
while (p[j] > x)
j--;
if (i < j)
{
if (p[i] == p[j])
{
if (i<mid)
i++;
if (j>mid)
j--;
}
else
{
temp = p[i];
p[i] = p[j];
p[j] = temp;
}
count ++;
}
}
quicksort(left,j-1,p);
quicksort(j+1,right,p);
}
return count;
}
Output redirection in bash can be accomplished with >.
For example, if you want to redirect the output of myprog to the file myout, you would use:
./myprog >myout
To time a program's execution, you can use the time command, like so:
time ./myprog
It will count the total amount of time elapsed since your program started until it exited (usually referred to as the wall-clock time), the amount of time you spend in user-space code and the amount of time spent executing kernel code (executing syscalls, for example, as part of printing the output).
So, to time your program and redirect output to a file, you would do this:
time ./myprog >myout
As others have mentioned in the comments, these are relatively easy tasks, you could probably find this information in a few seconds. Please make sure to do some research in the future before posting new questions. Good luck with your project!
Note: This, of course, assumes you have a different program for each sorting algorithm. If you'd rather stick to a single executable, I suggest you look at Execution time of C program to learn how to time the execution of each function.
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 )
The program I"m trying to finish is a program using the bubble sort algorithm. I am not sure what is the problem or in which function the problem is in. The problem is the program does not sort the array in properly. (It also must be arranged in ascending order).
Here is the code:
#include <stdio.h>
#include "simpio.h"
void getArray (int arr[], int size);
void sortArray (int arr[], int size);
void swap (int arr[], int num, int number);
void dispArray (int arr[], int size);
bool checkBigger (int arr[], int num, int number);
main()
{
int size;
printf("Enter number of elements: ");
size=GetInteger();
int arr[size];
getArray(arr, size);
sortArray(arr, size);
dispArray(arr, size);
getchar();
}
void getArray (int arr[], int size)
{
int num;
printf("Please enter the value of the elements: \n");
for(num=0; num<size; num++)
{
arr[num]=GetInteger();
}
}
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=num+1;
checkBigger(arr, num, number);
}
}
}
void swap (int arr[], int num, int number)
{
int tem;
tem=arr[num];
arr[num]=arr[number];
arr[number]=tem;
}
void dispArray (int arr[], int size)
{
int num;
printf("The sorted list is:\n");
for(num=0; num<size; num++)
{
printf("%d\t", arr[num]);
}
}
bool checkBigger (int arr[], int num, int number)
{
if(arr[num]>arr[number])
{
swap(arr, num, number);
}
}
Thank you very much.
void sortArray (int arr[], int size)
{
int num, number, d;
for(num=0;num<size-1;num++)
{
for(d=0; d<size-num-1; d++)
{
number=d+1;
checkBigger(arr, d, number);
}
}
}
pretty sure your problem is with you algorithm, try to simulate your algorithm in pen and paper. it will help your understanding of your code and the algorithm better :)
for your convenience here i am including a bubble sort algorithm i did some while ago
void bubbleSort( int a[], int n)
{
int i,j,temp; // for a={1,2,3,4,5} n is 5
n = n - 1; // bcz otherwise it will get out of index
for(i=0; i<n; i++)
{
for(j=0; j<n-i; j++)
{
if(a[j]>a[j+1])
{
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
}
}
i hope this helps
All I follow from the above examples is an implementation of the exchange sort.
The exchange sort on the outer loop checks each entry in the table against the first element, exchanging when necessary. At then end of the inner loop, the lowest element is in position 1, then it begins with position 2, comparing it to the remaining elements, and doing an exchange. Even if the array was already in order, the sort cannot stop. It has to do a n*(n-1) compares. An array of 50 elements, already sorted will do 50*49 comparisons.
The bubble sort works differently
set a swap flag to zero. Then
slide along the array, comparing position(i) to position(i+1). If a swap takes place, you do the sort again.
here is some pseudo code.
swap = 0
do {
for (i=o;i< no-elements-1;i++) {
if (array[i] > array[i+1])
{
do the exchange
set swap=1
}
/**/
} while (swap == 1);
The above illustrates the bubble sort.
Note. if the data is in order, there is no swap and there is no second loop. The sort algorithm is able to quit early.
if a fifty element array is in order, the sort would have done 50 comparisons and would have stopped.
The exchange sort, which is described earlier would have to do 50*49 or 2450 comparisons.
// BUBBLE SORT.
#include <stdio.h>
#define MAX 20
int main()
{
int arr[MAX];int no;
printf("PLEASE ENTER THE CURRENT SIZE OF THE ARRAY\n");
scanf("%d",&no);
int i;
printf("PLEASE ENTER THE ELEMENTS OF THE ARRAY\n");
for(i=0;i<no;i++)
scanf("%d",&arr[i]); /*reading the elements*/
/* sorting begins*/
int j,k,l;
int temp;
int flag=0;
for(k=0;k<no-1;k++)
{
flag=0;
j=k;
for(i=0;i<no-j-1;i++) /* not going to the part that has been sorted*/
{
if(arr[i]>arr[i+1])
{
flag=1;
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
else
continue;/* not necessary*/
}
if(flag==0) /*implies that the array is alraedy sorted*/
break;
}
printf("THE SORTED LIST:\n\n");
for(i=0;i<no;i++)
printf("%d\n",arr[i]);
}