分享

FindKthelement

 Lukies_图书馆 2019-12-09

#include <iostream>

#include<stdlib.h>

#include<fstream>

using namespace std;

int temp;int i,j;

void print(ofstream &write,int *a){

     write<<endl;

    for(int i=0;i<10;i++){

write<<a[i]<<' ';

    }

    write<<endl;

}

int FindKthelement(ofstream &write,int *a,int left,int right,int k){

int judge=a[left];i=left;left++;j=right;

print(write,a);

write<<"Moss: u have just made a recursion.This time left="<<left<<" right="<<right<<" k="<<k<<" judge="<<judge<<" i="<<i<<" j="<<j<<endl;

while(1){

while(a[left]<=judge){left++;}

while(a[right]>judge){right--;}

if(right>left){write<<"switch "<<a[left]<<" and "<<a[right]<<endl;temp=a[left];a[left]=a[right];a[right]=temp;}

else {break;}

}

write<<"break: left is "<<left<<" while right is "<<right<<endl;

if(k==left){return judge;}

else if(k<=left){temp=a[left-1];a[left-1]=a[i];a[i]=temp;right=left-2;write<<"choose the left.";FindKthelement(write,a,i,right,k);}

else{temp=a[left-1];a[left-1]=a[i];a[i]=temp;write<<"choose the right.";FindKthelement(write,a,right+1,j,k);}

}

int main()

{

    int a[10]={4,9,0,1,2,6,5,8,3,7};

//               4 3 0 1 2 6 5 8 9 7

ofstream write;

write.open("Findkthelement.txt");

write<<FindKthelement(write,a,0,9,10);

//int a[3]={5,9,1};

//write<<FindKthelement(a,0,2,2,3);

 //                0 1 2 3 4 5 6 7 8 9

//                {4,9,0,1,2,6,5,8,3,7};

//                 4 3 0 1 2 6 5 8 9 7

   return 0;

}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多