Ticker

6/recent/ticker-posts

Program to find kth smallest element in C (using bubble sort)

 

Program to find  kth smallest element in C 

In this program find kth smallest element so first user enter the unsorted array element then using function first sort the array element using bubble sort(In which array element is compare with adjacent element). 

for(i=lb;i<=ub;i++)
    {
    for(j=lb;j<=ub-i-1;j++)
    {
    if(a[j]>a[j+1])
    {
           temp=a[j];
           a[j]=a[j+1];
           a[j+1]=temp;
    }
    }
    }


After sort the array element print the kth smallest element (k-1) because kth smallest element placed at k-1 index.

printf("%d",a[k-1]);

For example

if n=5

a={1,23,67,3,89}

k=2(means find 2nd smallest element)

first sort array using bubble sort

a={1,3,23,67,89}

a[0]=1

a[1]=3

a[2]=23

a[4]=67

a[5]=89

so 2nd(k) smallest element at index 1(k-1)

so 2nd smallest element is 3

C code to find kth smallest element

#include<stdio.h>
void smallkth(int a[],int lb,int ub,int k);
int i;
void main()
{
    int a[10];
     int n;
     int k;
     printf("total number of element");
     scanf("%d",&n);
     for(i=0;i<n;i++)
     scanf("%d",&a[i]);
     printf("enter kth small element you want to search");
     scanf("%d",&k);
     smallkth(a,0,n-1,k);
}
void smallkth(int a[],int lb,int ub,int k)
{
    int j;
    int temp;
    for(i=lb;i<=ub;i++)
    {
    for(j=lb;j<=ub-i-1;j++)
    {
    if(a[j]>a[j+1])
    {
           temp=a[j];
           a[j]=a[j+1];
           a[j+1]=temp;
    }
    }
    }
    printf("%d",a[k-1]);
}

Output
total number of element5 12 1 2 34 5 enter kth small element you want to search5 34



Post a Comment

0 Comments