C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING
Find the Kth-Largest Array Element
Learn how to find the kth-largest array element using a clear C program.
PROBLEM UNDERSTANDING
Input and expected output
Sample input
6 7 10 4 3 20 15 3
Sample output
3th largest = 10
COMPLETE C PROGRAM
Complete C implementation
#include <stdio.h>
int main(void)
{
int size, values[100], rank;
scanf("%d", &size);
if (size < 1 || size > 100) return 1;
for (int index = 0; index < size; index++) scanf("%d", &values[index]);
scanf("%d", &rank);
if (rank < 1 || rank > size) return 1;
for (int start = 0; start < size - 1; start++) {
int maximum = start;
for (int index = start + 1; index < size; index++)
if (values[index] > values[maximum]) maximum = index;
int temporary = values[start]; values[start] = values[maximum]; values[maximum] = temporary;
}
printf("%dth largest = %d\n", rank, values[rank - 1]);
return 0;
}CURRENT STEP
SELECTED LINE
EXPECTED OUTPUT FOR THE SAMPLE
3th largest = 10
Step 0 of 0
PROGRAM EXPLANATION
Algorithm and explanation
- Read the required input values.
- Sort in descending order and select the element at index K−1.
- Display the computed result.
Sort in descending order and select the element at index K−1.
EFFICIENCY
Time and space complexity
Time complexity
O(n²)
Auxiliary space
O(1)
DEBUGGING CHECKLIST
Common mistakes
Check this
Use the correct format specifier for every variable.
Check this
Initialize variables before using their values.
Check this
Check braces, semicolons and input order carefully.
Try it yourself
Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.
