Youd better pay attention to the hint which is gived already

You\'d better pay attention to the hint which is gived already.Thanks.

Consider a problem of finding the k-th smallest element from vector A. Complete the following function. float kthSmallest (const vector& A, int k) {}

Solution

#include<iostream>
#include<stdlib.h>
#include<vector>
using namespace std;

int partition(vector<float> &A, int start, int end){
   int i= start+1;
    int j = i;
    int pivot = start;
     for(; i<end; i++){
        if(A.at(i) < A.at(pivot)){
            swap(A.at(i),A.at(j));
            j++;
        }
    }
    if(j<=end){
        swap(A.at(pivot),A.at(j-1));
    }
    for(i=0;i<10;i++){
        cout<<\" \" <<A.at(i);
    }
    cout<<\"\ \";
        return j-1;
}
float kthSmallest(vector<float> &A, int start, int end, int K){

   int part ;
    if(start <end) {
        part = partition(A, start, end);
            if(part == K-1){
                cout<<\"\ kth smallest element : \"<<A.at(part)<<\"\ \";
                return A.at(part);
            }
        if(part>K-1){
            kthSmallest(A, start, part, K);
        }
        else{
            kthSmallest(A, part+1, end, K);
        }
    }
}
int main(){

        int k; float a[10] ;
        vector<float> array ;
        cout<<\"Enter elements : \ \";
        for(int i= 0; i<10;i++)
        {
                cin>>a[i];
                array.push_back(a[i]);
        }

        int n = 10;
        cout<<\"Enter value of k : \"; cin>>k;
        array[0] = kthSmallest(array, 0, n, k);
        return 0;
}
       

You\'d better pay attention to the hint which is gived already.Thanks. Consider a problem of finding the k-th smallest element from vector A. Complete the follo
You\'d better pay attention to the hint which is gived already.Thanks. Consider a problem of finding the k-th smallest element from vector A. Complete the follo

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site