三種簡單的排序寫下貼上

來源:互聯網
上載者:User

標籤:

void Qsort(int *a,int L,int R) {
    if(L>=R) return ;
    int p=L,q=R;
    int val=a[L];
    while(p!=q) {
        while(p<q&&a[q]>val) q--;
        if(p<q) a[p++]=a[q];
        while(p<q&&a[p]<=val) p++;
        if(p<q) a[q--]=a[p];
    }
    a[p]=val;
    Qsort(a,L,p-1);
    Qsort(a,p+1,R);
}

void mergeSort(int *a,int *t,int L,int R) {
    if(L>=R) return ;
    int mid=(L+R)>>1;
    mergeSort(a,t,L,mid);
    mergeSort(a,t,mid+1,R);
    int p=L,q=mid+1,i=L;
    while(p<=mid&&q<=R) {
        t[i++]=a[p]<=a[q]?a[p++]:a[q++];
    }
    while(p<=mid) t[i++]=a[p];
    while(q<=R) t[i++]=a[q];
    for(int i=L;i<=R;i++) a[i]=t[i];
}

void heapAdjust(int *a,int pos,int sz) {
    if(pos>sz/2) return ;
    int Lchild=pos*2,Rchild=pos*2+1;
    int Min=pos;
    if(Lchild<=sz&&a[Lchild]>a[Min]) {
        Min=Lchild;
    }
    if(Rchild<=sz&&a[Rchild]>a[Min]) {
        Min=Rchild;
    }
    if(Min!=pos) {
        swap(a[pos],a[Min]);
        heapAdjust(a,Min,sz);
    }
}
void buildHeap(int *a,int sz) {
    for(int i=sz/2;i>=1;i--) {
        heapAdjust(a,i,sz);
    }
}
void HeapSort(int *a,int sz) {
    buildHeap(a,sz);
    for(int i=sz;i>=1;i--) {
        swap(a[1],a[i]);
        heapAdjust(a,1,i-1);
    }
}

三種簡單的排序寫下貼上

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.