2008年11月29日 星期六

Randomized-Select to find the ith smallest element

// Find the ith smallest element of the array A[p..r]. Using non-recursive programming.
// Input file:void
// Output:Stdout (show on monitor)

int Randomized_Select(char A[],int p,int r,int i)
{
 if(p==r)
  return A[p];
 int q=Randomized_Partition(A,p,r);
 int k=q-p+1;
 if(i==k) // the pivot is the answer
  return A[q];
 else if(ii-k);
}

// Using randomized method to find the KEY
int Randomized_Partition(char A[],int p,int r)
{
 int i=rand()%(r-p+1)+p;
 Swap(A,r,i);
 return Partition(A,p,r);
}

// Comparision and divide (1.> KEY 2.<= KEY)
int Partition(char A[],int p,int r)
{
 int x=A[r];
 int i=p-1;
 int j;
 for(j=p;j<=r-1;j++)
  if(A[j]<=x)
   Swap(A,++i,j);
 Swap(A,i+1,r);
 return i+1;
}

// Exchange two elements of the data
void Swap(char A[],int i,int j)
{
 int temp=A[i];
 A[i]=A[j];
 A[j]=temp;
 return;
}

沒有留言: