Multi-Threaded Bubble sort | Newbie | | Join Date: Sep 2007
Posts: 1
| |
I am trying to create a multi-threaded bubblesort but continue to get nothing. Here is my code, can someone help. Thanks -
#include <stdio.h>
-
#include <stdlib.h>
-
#include <pthread.h>
-
-
void *bubblesortup(int *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(int *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,43,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, &bubblesortup, (void *)a);
-
pthread_create( &thread2, NULL, &bubblesortdn, (void *)a);
-
-
}
-
|  | AdministratorVoR | | Join Date: Feb 2006 Location: South West UK
Posts: 6,162
| | | re: Multi-Threaded Bubble sort
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.
| | | | /bytes/about
We are a network of experts and professionals in IT and software development that help one another with answers to tough questions and share insights.
Get the best answers to your questions from over 226,295 network members.
|