Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

就是第K小的数。。。。。(附代码)

Posted by WHQ557 at 2012-09-06 11:03:23 on Problem 2388

代码较乱 将就着看吧……



#include<stdio.h>
#include<string.h>

void swap(int *a,int *b){
//    *a+=*b;
//    *b=*a-*b;
//    *a-=*b;
//    这种方法WA了 我怀疑是溢出……
     int c=*a;
    *a=*b;
    *b=c;
}

int n;
int a[10005];

void my_sort(int x,int y,int k){
    int key=a[x];
    int front=x;
    int rear=y-1;
    if(x>=y-1) return;
    while(front<=rear){
        while(front<=rear&&a[front]<=key) ++front;
        while(front<=rear&&a[rear]>=key) --rear;
        if(front<rear){
            swap(&a[front],&a[rear]);
//a[front]+=a[rear];a[rear]=a[front]-a[rear];a[front]-=a[rear];
//  没有调用 swap 函数 也WA 真的可能是溢出了……
            ++front;
            --rear;
        }
    }
    swap(&a[x],&a[rear]);
//a[x]+=a[rear];a[rear]=a[x]-a[rear];a[x]-=a[rear];
    if(x<=k&&k<rear) my_sort(x,rear,k);
    if(rear+1<=k&&k<y) my_sort(rear+1,y,k);
}

main(){
    while(~scanf("%d",&n)){
        int i,k;
        for(i=0;i<n;++i){
            scanf("%d",&a[i]);
        }
        k=n>>1;
        my_sort(0,n,k);
        printf("%d\n",a[k]);
    }
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator