Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Need help with my ksmall program. I get an error saying segmentation dump. Thank

ID: 3872962 • Letter: N

Question

Need help with my ksmall program. I get an error saying segmentation dump. Thanks

#include<iostream>

using namespace std;


int ksmall(int*, int, int , int);
void swap(int*, int*);

int main()
{
    int SIZE = 10;
    int target;
    int begining=0;
    int ending=SIZE-1;

    int *array1= new int[SIZE];

    cout << "Enter 10 integers: " << endl;
    for (int i=0; i<SIZE; i++)
    {
       cin>>array1[i];
    }

    cout << " What is the Kth smallest number you want to determine; Enter a number between 1 to ten:   ";
    cin >> target;
    cout<< ksmall (array1, target, begining, ending);
      delete [] array1;
      array1=nullptr;
       return 0;
}

int ksmall(int* arr, int K, int first, int last)
{

int a=*(arr+first);
int i=first+1;
for(int j=first+1;j<=last; j++)

{
    if(arr[j]<=a)
    {
        swap(*(arr+i), *(arr+j));
         i++;
    }
}


swap(*(arr+i), *(arr+first));

int p= i;

if(K<(p-first+1))
{
    return ksmall(arr, K, first, p-1);
}
else if (K==(p-first+1))
{
    return *(arr+p);
}
else
{
    return ksmall(arr, K-(p-first+1), p+1, last);
}
}


void swap(int *m, int *n)
{
    int temp=*m;
    *m=*n;
    *n=temp;
}

Explanation / Answer

#include<iostream>

using namespace std;


int ksmall(int*, int, int , int);
void swap(int*, int*);

int main()
{
    int SIZE = 10;
    int target;
    int begining=0;
    int ending=SIZE-1;

    int *array1= new int[SIZE];

    cout << "Enter 10 integers: " << endl;
    for (int i=0; i<SIZE; i++)
    {
       cin>>array1[i];
    }

    cout << " What is the Kth smallest number you want to determine; Enter a number between 1 to ten:   ";
    cin >> target;
    cout<< ksmall (array1, target, begining, ending);
      delete [] array1;
      array1=NULL;
       return 0;
}

int ksmall(int* arr, int K, int first, int last)
{

int a=*(arr+first);
int i=first;
for(int j=first+1;j<=last; j++)

{
    if(arr[j]<=a)
    {
        swap(*(arr+i), *(arr+j));
         i++;
    }
}


swap(*(arr+i), *(arr+first));

int p= i;

if(K<(p-first+1))
{
    return ksmall(arr, K, first, p-1);
}
else if (K==(p-first+1))
{
    return *(arr+p);
}
else
{
    return ksmall(arr, K-(p-first+1), p+1, last);
}
}


void swap(int *m, int *n)
{
    int temp=*m;
    *m=*n;
    *n=temp;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote