积少成多

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

计数排序

class {
public:
 ///
    void CountingSort(int *A,int *B,int *Order,int N,int K){
        int *C = new int[K+1];
        int i;
        memset(C,0,sizeof(int)*(K+1));
        for(i = 1;i<=N;i++){///
            C[A[i]]++;
        }


        for(i = 2;i<=K;i++){
            C[i] += C[i-1];
        }
        cout<<endl;
        for(int i = 1;i<(K+1);i++){
            cout<<C[i]<<" ";
        }cout<<endl;

        for(i=N;i>=1;i--){
            B[C[A[i]]] = A[i];
            Order[C[A[i]]] = i;
            C[A[i]]--;
        }
    }

    void testCS(){
        ///=============
    int *A,*B,*Order,N = 15,K = 10,i;
    A = new int[N+1];
    B = new int[N+1];
    Order = new int[N+1];
    for(i = 1;i<=N;i++){
        A[i] = rand()%K+1;
    }
    printf("Before cs: \n");
    for(i = 1;i<=N;i++){
        printf("%d ",A[i]);
    }
    CountingSort(A,B,Order,N,K);
    printf("\nafter cs:\n");
    for(i = 1;i<=N;i++){
        printf("%d ",B[i]);
    }
    printf("\nOrder:\n");
    for(i = 1;i<=N;i++){
        printf("%d ",Order[i]);
    }
    cout<<"done"<<endl;
    ///================
    }
};

 

 

桶排序

class {
public:
    ///
    const int BUCKET_NUM = 10;
    ListNode *insert(ListNode *head, int val){
        ListNode dummyNode(-1);
        ListNode *newNode = new ListNode(val);
        ListNode *prev,*curr;
        dummyNode.next = head;
        prev = &dummyNode;
        curr = head;
        while(curr && curr->val <= val){
            prev = curr;
            curr = curr->next;
        }///find location to insert; prev->next
        newNode->next = curr;
        prev->next = newNode;
        return dummyNode.next;
    }

    ListNode *mergebucket(ListNode *head1,ListNode *head2){
        ListNode dummy(-1);
        ListNode *h = &dummy;
        while(head1 && head2){
            if(head1->val <= head2->val){
                h->next = head1;
                head1 = head1->next;
            }else{
                h->next = head2;
                head2 = head2->next;
            }
            h = h->next;
        }
        if(head1) h->next = head1;
        if(head2) h->next = head2;
        return dummy.next;
    }

    void BucketSort(int n,int arr[]){
        vector<ListNode*> buckets(BUCKET_NUM,nullptr);
        for(int i = 0;i<n;i++){
            int index = arr[i]%BUCKET_NUM;
            ListNode *head = buckets[index];
            buckets[index] = insert(head,arr[i]);
        }///
        ListNode *head = buckets[0];
        for(int i = 1;i<BUCKET_NUM;i++){
            head = mergebucket(head,buckets[i]);
        }

        for(int i = 0;i<n;i++){
            arr[i] = head->val;
            head = head->next;
        }
    }
};

 

posted on 2016-06-22 15:40  x7b5g  阅读(170)  评论(0编辑  收藏  举报