link_t mergesort_list(link_t head)
{
	link_t heada,headb;
	link_t x,t;

	if(head==NULL || head->next==NULL){
		return(head);
	}

	heada=head;
	headb=head;
	x=head->next;
	while(x!=NULL && x->next!=NULL){
		headb=headb->next;
		x=x->next->next;
	}

	t=headb;
	headb=t->next;
	t->next=NULL;

	heada=mergesort_list(heada);
	headb=mergesort_list(headb);
	head=merge_list(heada,headb);

	return(head);
}
Example #2
0
/* Sorts a linear list, given a comparison function.
   Note: This uses a variant of mergesort that is *not* a stable sorting
   algorithm.  */
Keyword_List *
mergesort_list (Keyword_List *list, Keyword_Comparison less)
{
  if (list == NULL || list->rest() == NULL)
    /* List of length 0 or 1.  Nothing to do.  */
    return list;
  else
    {
      /* Determine a list node in the middle.  */
      Keyword_List *middle = list;
      for (Keyword_List *temp = list->rest();;)
        {
          temp = temp->rest();
          if (temp == NULL)
            break;
          temp = temp->rest();
          middle = middle->rest();
          if (temp == NULL)
            break;
        }

      /* Cut the list into two halves.
         If the list has n elements, the left half has ceiling(n/2) elements
         and the right half has floor(n/2) elements.  */
      Keyword_List *right_half = middle->rest();
      middle->rest() = NULL;

      /* Sort the two halves, then merge them.  */
      return merge (mergesort_list (list, less),
                    mergesort_list (right_half, less),
                    less);
    }
}
/*
** The implementation of top-down list mergesort that carries the
** list length as a parameter to the recursive procedure and uses
** it to split the lists.
*/
link_t mergesort_list(link_t head,int length)
{
	link_t heada,headb;
	link_t t;
	int middle=(length+1)/2;
	int i;

	if(head==NULL || head->next==NULL){
		return(head);
	}

	heada=head;
	headb=head;
	for(i=1;i<middle;i++){
		headb=headb->next;
	}

	t=headb;
	headb=t->next;
	t->next=NULL;

	heada=mergesort_list(heada,middle);
	headb=mergesort_list(headb,length-middle);
	head=merge_list(heada,headb);

	return(head);
}
Example #4
0
KeywordExt_List *
mergesort_list (KeywordExt_List *list,
                bool (*less) (KeywordExt *keyword1, KeywordExt *keyword2))
{
  return
    static_cast<KeywordExt_List *>
      (mergesort_list (static_cast<Keyword_List *> (list),
                       reinterpret_cast<Keyword_Comparison> (less)));
}
int main(int argc,char *argv[])
{
	link_t head,t;
	int N=atoi(argv[1]);
	int i;

	srand((unsigned)time(NULL));

	head=new_node(rand()%N);
	for(i=1;i<=N-1;i++){
		t=new_node(rand()%N);
		insert_next(head,t);
	}
	print_list(head);

	head=mergesort_list(head,N);
	print_list(head);

	return(0);
}