#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; } |
|
來自: Lukies_圖書館 > 《公選》