Summary: This C program finds the Kth smallest and Kth largest elements from an array by sorting the array in ascending order using Bubble Sort. It then prints these values along with appropriate ordinal suffixes.
#include <stdio.h>
// Function to perform bubble sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int n, k;
// Get the number of elements
printf("Enter the number of elements: ");
scanf("%d", &n);
// Check constraints
if (n < 1 || n > 1000) {
printf("Invalid number of elements! Please enter a value between 1 and 1000.\n");
return 1;
}
int arr[n];
// Get the array elements
printf("Enter the elements: ");
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
// Get the value of k
printf("Enter the value of k: ");
scanf("%d", &k);
// Check constraints for k
if (k < 1 || k > n) {
printf("Invalid value of k! Please enter a value between 1 and %d.\n", n);
return 1;
}
// Sort the array in ascending order using bubble sort
bubbleSort(arr, n);
// Find the Kth smallest and Kth largest elements
int kth_smallest = arr[k - 1]; // Kth smallest element is at index k-1
int kth_largest = arr[n - k]; // Kth largest element is at index n-k
// Print the results
printf("%d", k);
// Handling ordinal suffixes for English (1st, 2nd, 3rd, 4th, etc.)
if (k % 10 == 1 && k % 100 != 11) {
printf("st");
} else if (k % 10 == 2 && k % 100 != 12) {
printf("nd");
} else if (k % 10 == 3 && k % 100 != 13) {
printf("rd");
} else {
printf("th");
}
printf(" smallest element: %d\n", kth_smallest);
printf("%d", k);
if (k % 10 == 1 && k % 100 != 11) {
printf("st");
} else if (k % 10 == 2 && k % 100 != 12) {
printf("nd");
} else if (k % 10 == 3 && k % 100 != 13) {
printf("rd");
} else {
printf("th");
}
printf(" largest element: %d\n", kth_largest);
return 0;
}
Program Overview:
This program finds the Kth smallest and Kth largest elements from an array by sorting the array in ascending order using Bubble Sort. It also displays the results with appropriate ordinal suffixes.
bubbleSort():The bubbleSort() function sorts the array by comparing adjacent elements and swapping them if they are in the wrong order. This process is repeated until the array is sorted.
n.n is between 1 and 1000.n elements of the array.k is input by the user.k is between 1 and n.bubbleSort() is used to sort the array in ascending order.k - 1.n - k.k is outside the valid range.O(n^2) due to the nested loops used in bubble sort.O(1) as the operations are performed in-place with minimal extra space.