关闭

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

标签: 快速排序海量数据中位数
96人阅读 评论(0) 收藏 举报
分类:

快速排序找中位数


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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:30016次
    • 积分:788
    • 等级:
    • 排名:千里之外
    • 原创:41篇
    • 转载:67篇
    • 译文:0篇
    • 评论:1条
    最新评论