Kth largest array

So I'm trying to make a function that prints out the kth largest number in the array but its not working. Can you guys help me find out whats wrong with my code?
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
int Recursion::kthLargest(int start, int endpoint, int k){
	int pivot=start; //first element of the array
	int left=start;
	int right=endpoint;
	while(left<=right)
	{
		while(left<=right && arr[left]<=arr[pivot]){ //scans from left to right until we find a value larger than pivot
			++left; //if value at left is larger than pivot we need to swap
		}
		while(left<=right && arr[right]>=arr[pivot]){
			--right; //if value at right is larger than pivot we need to swap
		}
		if(left<right){ //swap if valid
		swap(left,right);
		}
	}
	//after loop pivot position should be on the right position
	swap(pivot,right);
	if(k==right+1){
		cout<< arr[right]; //prints out right position of value set
	}
	else if(k>right+1){ //divide values into two groups, kth largest must be on right half
		return kthLargest(right+1, endpoint, k);
	}
	else{
		return kthLargest(start,right-1,k);
	}
}
You should actually explain how your function works rather than leaving it to the imagination what it is actually doing.
My guess is that you are not returning the kth largest, instead you are just printing it, so line 20 should actually be return arr[right];

If you don't need it to be recursive, then you can just place everything in a balanced binary search tree and print the kth largest
Topic archived. No new replies allowed.