zoukankan      html  css  js  c++  java
  • 快速选择问题

    输入n个整数和一个正整数k(1<=k<=n),输出这k[n]。

    快速排序

    将序列分成两部分,大于tmp小于tmp

    分别对两部分进行排序

    不要合并

    void QuickSort(RecType R[],int s,int t,int k)
    {
        int i=s,j=t;
        RecType tmp;
        if(s<t)
        {
            tmp=R[s];
            while(i!=j)
            {
                while(j>i&&R[j].key>=tmp.key)
                    j--;
                R[i]=R[j];
                while(i<j&&R[i].key<=tmp.key)
                    i++;
                R[j]=R[i];
            }
            R[i]=tmp;
            QuickSort(R,i+1,t,k);
            QuickSort(R,s,i-1,k);
        }
    }
    //代码来自数据结构-李春葆

    O(n)的时间内将k[n]找出来

    #include<iostream>
    using namespace std;
    struct RecType
    {
        int key;
    };
    int rk;
    void QuickSort(RecType R[],int s,int t,int k)
    {
        int i=s,j=t;
        RecType tmp;
        if(s<t)
        {
            tmp=R[s];
            while(i!=j)
            {
                while(j>i&&R[j].key>=tmp.key)
                    j--;
                R[i]=R[j];
                while(i<j&&R[i].key<=tmp.key)
                    i++;
                R[j]=R[i];
            }
            R[i]=tmp;
            if(k>i)
                QuickSort(R,i+1,t,k);
            else if(k<i)
                QuickSort(R,s,i-1,k);
            else
                rk=R[k].key;
        }
        rk=R[k].key;
    }
    int main()
    {
        int s=1,t,k;
        RecType r[100];
        cin>>t>>k;
        for(int i=1;i<=t;i++)
            cin>>r[i].key;
        QuickSort(r,s,t,k);
        cout<<rk<<endl;
    }
    
  • 相关阅读:
    401. Binary Watch
    46. Permutations
    61. Rotate List
    142. Linked List Cycle II
    86. Partition List
    234. Palindrome Linked List
    19. Remove Nth Node From End of List
    141. Linked List Cycle
    524. Longest Word in Dictionary through Deleting
    android ListView详解
  • 原文地址:https://www.cnblogs.com/ke-yi-/p/10175819.html
Copyright © 2011-2022 走看看