利用快排找中位数【未完成】

快速排序找中位数


int sort(int* R,int low,int high) ;   
int median1(int *R,int n);    
int median2(int* R,int low,int high);
    const int mmax = 10000001;  // 9999;
    int a[mmax] = {1, 2, 4, 6, 3, 7, 5, 9, 8, 11, 3};  //待排数组  
    int len;
    int ans;
int partition(int* R,int low ,int high)
{
    int t = R[low];
    while(low<high)
    {
        while((low<high)&&(R[high]>=t))
            high--;
        R[low] = R[high];
        while((low<high)&&(R[low]<=t))
            low++;
        R[high] = R[low];
    }
    R[low] = t;
    return low;
}


void quick_sort1(int *R,int n)          //该函数进行sort过程的调用
{         
    sort(R,0,n-1);
}
void quick_sort2(int *R,int n)          //该函数进行median1过程的调用
{            
    median1(R,n);
}
void quick_sort3(int *R,int n)          //该函数进行median2过程的调用
{         
    median2(R,0,n-1);
}
<pre name="code" class="cpp">int sort(int* R,int low,int high)
{
    if(low>=high)
        return 0;
    int pivotloc = 0;
    pivotloc = partition(R,low,high);
    sort(R,low,pivotloc-1);
    sort(R,pivotloc+1,high);
}

int median1(int *R,int n){int left = 0;int right = n-1;int mid = (left + right)/2;int num;while(1){ num = partition(R,left,right); if(num == mid) break; if(num<mid) //说明在右边 left = num + 1; if(num>mid) right = num - 1;}return (n & 0x01)?R[mid]:(R[mid]+R[mid+1])/2;} int median2(int* R,int low,int high){if(low>=high) return 0;int mid = len/2;int pivotloc = 0; pivotloc = partition(R,low,high); if(pivotloc == mid){ ans=R[pivotloc];
return ans;
}
 if(pivotloc<mid) //说明在右边 median2(R,pivotloc + 1,high); if(pivotloc>mid) median2(R,low,pivotloc - 1);//return (n & 0x01)?R[mid]:(R[mid]+R[mid+1])/2;} void su(){ int len = mmax; srand( (unsigned)time( NULL ) ); for(int i = 0; i < len; i++){ a[i] = rand() % 100000000; } } int main(){ len = mmax; su(); clock_t start_time=clock(); //quick_sort1(a,len); //时间复杂度大 //cout<<a[len/2]<<endl; //cout<<ans<<endl; clock_t end_time=clock(); cout<< "Running time is: "<<static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000<<"ms"<<endl;//输出运行时间 start_time=clock(); quick_sort2(a,len); //可以 cout<<a[len/2]<<endl; //cout<<ans<<endl; end_time=clock(); cout<< "Running time is: "<<static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000<<"ms"<<endl;//输出运行时间 start_time=clock(); //quick_sort3(a,len); //有时会输出0 //cout<<a[len/2]<<endl; //cout<<ans<<endl; end_time=clock(); cout<< "Running time is: "<<static_cast<double>(end_time-start_time)/CLOCKS_PER_SEC*1000<<"ms"<<endl;//输出运行时间 system("pause"); }

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值