Search code examples
linuxgccbubble-sort

Bubble Sort Time C program


The test is to create an array of size 10000. Initialize it with the values 10000 down to 1 and then use a bubble sort to reverse the order.As a bubble sort is one of the worst possible sorts, this should take a fairly long time. However, the resolution of the timing is limited.

The solution is to put the task inside a loop that repeats it a thousand or a million times—whatever it takes to get the numbers up to something you can deal with. I am getting errors in my code. Please see my code below.

The following commands are run on linux:
gcc -o sort sort.c -O2
time ./sort

gcc -m32 -o sort sort.c -O2 -march=pentium4
time ./sort

#include <stdio.h>

void bubbleSort(int numbers[], int array_size)
{

    int i, j, temp;

    for (i =0; i <array_size; i++)
    {
        for (j =0; j<array_size-1; j++)
        {
            if (numbers[j] > numbers[j+1])  {
                temp = numbers[j];
                numbers[j] = numbers[j+1];
                numbers[j+1] = temp;
            }
        }
    }
}

int main(void)
{
    int array[10000];
    int i;

    for(i=10000;i!=0;i--)
    {
        array[i-1]=i;
    }
    bubbleSort(array,10000);
    for(i=0;i<10000;i++)
    {
        printf("%d\n",array[i]);
    }
    return 0;
}

Solution

  • The following code stores the numbers in the array in ascending order.

        for(i=10000;i!=0;i--)
        {
            array[i-1]=i;
        }
    

    Your sorting algorithm also sorts the numbers in ascending order, so you won't find any change to the numbers in the array.

            if (numbers[j] > numbers[j+1])  
            {
                temp = numbers[j];
                numbers[j] = numbers[j+1];
                numbers[j+1] = temp;
            }
    

    Change the above if as follows,

            if (numbers[j] < numbers[j+1]) 
            {
                temp = numbers[j];
                numbers[j] = numbers[j+1];
                numbers[j+1] = temp;
            }