Could anyone check my code? I'm not getting the right output when I'm trying to find the kth smallest.
This is the algorithm:
create a function int my_partition(int *anArray, int first, int last)
*anArray is the array being partitioned, first and last are the beginning and end of the section of the array where the pivot will be place. When it is done, my_partition will return the pivot index.
the value at anArray[first] is the pivot
two values are set: left_position is set to first + 1, right_position is set to last
while left_position < right_position
while anArray[left_position] is less than pivot
add on to left_position
while anArray[right_position] is greater than pivot
subtract on from right_position
if right_position > left_position
swap the values in anArray[left_position] and anArray[right_position]
increment left_position
decrement right_position
store values of anArray[right_position] in anArray[first]
store the pivot in anArray[right_position]
return right_position as the pivot index
test the kSmall by writing a main function where the array that is to be passed to the function must be generated as a dynamic array using new operator.\
My output:
Enter array size:
8
Enter 8 elements in array:
1
5
8
3
6
2
4
7
You entered:
1 5 8 3 6 2 4 7
Enter the value of k:
5
K’th smallest element: 0%
#include <iostream>
using namespace std;
int partition(int *anArray, int first, int last)
{
int pivot = anArray[first];
int left_side = first +1;
int right_side = last;
while (left_side <= right_side)
{
while (anArray[left_side] < pivot)
{
left_side++;
}
while (anArray[right_side] > pivot)
{
right_side--;
}
if (left_side < right_side)
{
int temp1 = anArray[left_side];
anArray[left_side] = anArray[right_side];
anArray[right_side] = temp1;
}
}
int temp2 = anArray[first];
anArray[first] = anArray[right_side];
anArray[right_side] = temp2;
return right_side;
}
int kSmall(int k, int *anArray, int first, int last)
{
int pivotIndex = partition(anArray, first, last);
if (k < pivotIndex - first + 1)
{
return kSmall(k, anArray, first, pivotIndex-1);
}
else if (k = pivotIndex - first +1)
{
return anArray[pivotIndex];
}
else
{
return (k - (pivotIndex - first + 1), anArray, pivotIndex + 1, last);
}
}
int main()
{
int size;
cout << "Enter array size: " << endl;
cin >> size;
int *arr = new int(size);
cout << "Enter " << size << " elements in array: " << endl;
for (int i=0; i<size; i++)
{
cin >> arr[i];
}
cout << "You entered: " << endl;
for (int i=0; i<size; i++)
{
cout << arr[i] << " " << endl;;
}
int k;
cout << "Enter the value of k: " << endl;
cin >> k;
int first = arr[0];
int last = arr[size];
cout << "K’th smallest element: " << kSmall(k,arr,first,last);
}