/**
 * Quicksort that delegates to helper thread the sorting of a sub-array
 * should a thread be available and if the problem size is sufficiently
 * large enough to warrant such an action.
 *
 * @param ar           array being sorted
 * @param cmp          comparison function to use
 * @param helper       context for helper thread
 * @param left         lower bound index position  (inclusive)    
 * @param right        upper bound index position  (inclusive) 
 */
void quickSort2(void **ar, int(*cmp)(const void *,const void *),
		THREAD_INFO *helper, int left, int right) {
  int p,n;

  if (left < right) {
    p = partition(ar, cmp, left, right);
    n = p - left;

    /** If helper already requested to help or problem too big, recurse. */
    if (helpRequested || n >= helper->threshold) {
      quickSort2(ar, cmp, helper, left, p-1);
    } else  {
      /** initialize helper variables and ask for help. */
      helper->left = left;
      helper->right = p-1;
      
      helpRequested = 1;
    }
    
    n = right - p;
    if (helpRequested || n >= helper->threshold) {
      quickSort2(ar, cmp, helper, p+1, right);
    } else {
      /** initialize helper variables and ask for help. */
      helper->left = p+1;
      helper->right = right;
      
      helpRequested = 1;
    }
  }
}
/**
 * Entry point for primary thread.
 * 
 * Once synchronized, launches the primary sort routine.
 * 
 * @param arg    thread context
 */
void quickSortEntry(void *arg) {
  THREAD_INFO *context = (THREAD_INFO *) arg;

  /** Wait until all threads ready to go. */
  pthread_barrier_wait(&barrier);

  /**
   * When we get here, all threads are synchronized. Note that
   * numElements is a global int which stores number of elements.
   */
  quickSort2(context->ar, context->cmp, context->helper,
	     0, numElements-1);

  /** Stop Helper thread. */
  done=1;

  /** Now wait for all threads again before exiting. */
  pthread_barrier_wait(&barrier);
}
Beispiel #3
0
int main(int argc, char* argv[])
{
    int len =   atoi(argv[1]);
    int array[len],array2[len];
    srand(time(NULL));
    int i;
    for(i=0;i<len;i++)  {array[i]=rand()%10000; array2[i]=array[i];}

    printf("排序前的数组---->\n");
    for(i=0;i<len;i++) printf("%d  ",array[i]); printf("\n");

    quickSort(array,0,len-1);
    printf("递归方法排序后的数组---->\n");
    for(i=0;i<len;i++) printf("%d  ",array[i]); printf("\n");

    quickSort2(array2,len);
    printf("循环方法排序后的数组---->\n");
    for(i=0;i<len;i++) printf("%d  ",array2[i]); printf("\n");

    return 0;
}