Multi-Threaded Bubble sort

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • flyfast81
    New Member
    • Sep 2007
    • 1

    #1

    Multi-Threaded Bubble sort

    I am trying to create a multi-threaded bubblesort but continue to get nothing. Here is my code, can someone help. Thanks

    [code=c]
    #include <stdio.h>
    #include <stdlib.h>
    #include <pthread.h>

    void *bubblesortup(i nt *a)
    {
    char i,j,hup;

    for (i=0; i<30; i++)

    for (j=0; j<30-1;j++)

    if (a[j]> a[j+1])
    {
    hup = a[j+1];
    a[j+1]=a[j];
    a[j]=hup;
    }
    }

    void *bubblesortdn(i nt *a)
    {
    char n,o,hdn;

    for (n=30; n>0; --n)
    for (o=30; 0+1; --n)

    if (a[o-1]>a[o])
    {
    hdn = a[o-1];
    a[o-1]=a[o];
    a[o]=hdn;
    }
    }





    int main(int argc, char *argv[])
    {
    pthread_t thread1;
    pthread_t thread2;
    int k,l,i;

    char a[] = {4,67,45,3,41,4 3,75,3,9,34,6,3 ,4,12,41,84,49, 33,65,74,54,12, 58,12,65,34,26, 99,85,1};
    pthread_create( &thread1, NULL, &bubblesortu p, (void *)a);
    pthread_create( &thread2, NULL, &bubblesortd n, (void *)a);

    }
    [/code]
    Last edited by Banfa; Sep 26 '07, 09:35 AM. Reason: Added [code]...[/code] round the code
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    You use the magic number 30 in many places, this should be the size of the array a using a magic number like tghis is asking for trouble and errors later on.

    The end condition for the j for loop is wrong, it can reduce by 1 for each iteration of the i for loop.

    The end condition for the o for loop is no existant, this is an inifinite loop. This end condition should depend on n.

    The bigest mistake though is that both threads simultaneously assess the array a. This is also asking for trouble and will likely not work and cause errors. In a multithreaded program it is important to ensure that any given piece of data is only accessed from 1 thread at a time otherwise data corruption can, and most probably will, occur.


    I do not think the bubble sort algorithm is ideally suited to multithreaded resolution, it is too simple.

    Comment

    Working...