Coding Challenge Day-10: Problem 1: Display the kth smallest element in an integer array

Hello! So I’m doing a 30 day coding challenge where I solve around 3-5 questions per day and thought of posting them here on my blog so that you guys can join the challenge too!

Welcome to Coding challenge Day 10: Problem 1! Be sure to post your answers, queries etc in the comments!

Problem: Display the kth smallest element in an integer array

Sample input: int [] array= {1,5,6,2,8,19,11,10,3,4};
Output: The 3 smallest element in array 1,5,6,2,8,19,11,10,3,4, is 3

Solutions:

  • Sort the array
  • display (k-1)th element
package array;

import java.util.Arrays;

public class Program009find_kth_smallest_element {
	
	public static void main (String [] args){
		
		int [] array= {1,5,6,2,8,19,11,10,3,4};
		int length= array.length;
		int k=3;
		
		System.out.print("The " +k +" smallest element in array ");
		
		for(int i=0; i<length; i++){
			System.out.print(array[i] + ",");
		}
		
		//bubble sort
		for(int i=0; i<length-1; i++){
			for(int j=0; j<length-i-1; j++){
				if(array[j]>array[j+1]){
					int temp= array[j];
					array[j]= array[j+1];
					array[j+1]=temp;
				}
			}
		}
		
		System.out.println(" is " + array[k-1]);
		
		System.out.println("Sorted: ");
		

		for(int i=0; i<length; i++){
			System.out.print(array[i] + ",");
		}
		
	}

}

Download Code

Happy Learning!!

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close