Introduction to Algorithms Sorting

count sort

void Sort(int a[],int& b[],int k)
{
   int c[k];
   for(int i=0;i<k;i++)
   {
       c[a[i]]++; //c[a[i]] stores the number of occurrences of a[i]
   }
   for(int i=1;i<k;i++)
   {
       c[i]+=c[i-1];//The sum of numbers smaller than i
   }
   for(int j=k-1;j>=0;j--)
   {
       b[c[a[j]]]=a[j];
       c[a[j]]--;
   }
}

Bucket sorting is used when the data range is small and the amount of data is large

Linear Algorithm for Selecting the ith Largest Number 

int patition(int a[],int p,int r)
{
    int x=a[r];
    int i=p-1;
    for(int j=p;j<r;j++)
    {
        if(a[j]<=x)
        {
            i++;
            swap(a[j],a[i]);
        }
    }
 swap(a[++i],x);
 return i;
}
int random_partition(int a[],int p,int r)
{
    int j=p+rand()%(r-p);
    patition(a,p,j);
    swap(a[j],a[r]);
    return patition(a,p,r);

}
int  Find(int a[],int p,int r,int i)
{
    if(p==r) return a[p];
    int j=random_partition(a,p,r);
    int k=j-p+1;
    if(k==i)
        return a[j];
    else if(i<k)
        return Find(a,p,k-1,i);
    else return Find(a,k+1,r,i-k);

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325805505&siteId=291194637