RSS
 

QuickSort

14 Dec

今天有点懒,这个是从 wikipedia 上摘下来的:

void swap(int *a, int *b)
{
  int t=*a; *a=*b; *b=t;
}

void quicksort(int arr[],int beg,int end)
{
	if (end  >= beg + 1)
  	{
  		int piv = arr[beg], k = beg + 1, r = end;

		while (k < r)
    		{
      			if (arr[k] < piv)
        			k++;
      			else
        			swap(&arr[k], &arr[r--]);
    		}
		if (arr[k] < piv){

			swap(&arr[k],&arr[beg]);

			quicksort(arr, beg, k);
			quicksort(arr, r, end);
		}else {
			if (end - beg == 1)
  				return;

			swap(&arr[--k],&arr[beg]);
			quicksort(arr, beg, k);
			quicksort(arr, r,   end);
		}
  	}

}
 
 

Tags: , ,

Leave a Reply

 
Note: Commenter is allowed to use '@User+blank' to automatically notify your reply to other commenter. e.g, if ABC is one of commenter of this post, then write '@ABC '(exclude ') will automatically send your comment to ABC. Using '@all ' to notify all previous commenters. Be sure that the value of User should exactly match with commenter's name (case sensitive).