Finding the kth smallest element in an array using recursion?

My goal is for the user to input a number and said number would direct them to the kth smallest number in the already generated array.

I'm relatively new to recursion and I'm being told to do this in recursion. I am already aware of the iterative (and better) solution to this but I'm having difficulty finding the recursive example. My code is below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <iostream>

using namespace std;

void moveToKthSmallest(int a[], int size, int k); 


int main() {

	int theArray[17] = {42, 5, 412, 56, 14, 98, 488, 4882, 24, 4, 9, 67, 9424, 2, 1, 3, 5};
	int num;

	cout << "Move to the kth smallest number in the array (size of 17): " << endl;
	cin >> num;
	moveToKthSmallest(theArray, 17, num);


	return 0;
}

void moveToKthSmallest(int a[], int size, int k) {
	int pivot = size / 2;
	int pivotValue = a[pivot];
	int index1 = 0, index2 = 0;
	int s1[size], s2[size];


	for (int i = 0; i < size; i++) {
		if (a[i] < pivotValue) {
			s1[index1] = a[i];
			index1++;
		}
	}

	for (int j = 0; j < size; j++) { 
		if (a[j] > pivotValue) {
			s2[index2] = a[j];
			index2++; 
		}
	}

	int s1Size = index1;
	int s2Size = index2;

	if (s1Size == k - 1) {
		cout << pivotValue;
	}

	else if (s1Size > (k - 1)) {
		moveToKthSmallest(s1, s1Size, k);
	}

	else if (s1Size < (k - 1)) {
		moveToKthSmallest(s2, s2Size, k - (s1Size - 1));
	}
}


This crashes after every run. I've used arrays, dynamic arrays, and vectors but alas, it crashes every time. Is there something that I am missing?
It is possible for size to be 0, and when it is you try to access elements of an array that do not exist.

Line 25 is illegal in C++.

This crashes after every run. I've used arrays, dynamic arrays, and vectors but alas, it crashes every time. Is there something that I am missing?

Try using vectors and replacing the [index] notation with .at(index). Or, with MVC++, just change switch to a debug target.
Topic archived. No new replies allowed.