Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- /*
- A function that takes an array and an integer K,
- and returns the Kth smallest integer in the array
- */
- int smallestElement(int arr[],int size,int k);
- int main()
- {
- int size,k;
- printf("Enter the size of the array: ");//asks the user for the size of the array
- scanf("%d",&size);// gets the size from the user
- int arr[size];// the declaration of the array
- printf("Enter the elements of the array\n");//asks the user for the elements of the array
- for(int i = 0; i< size ;i++)
- {
- scanf("%d",&arr[i]);// scanning the elements of the array 1 at a time
- }
- printf("Enter a number K to get the Kth smallest element in the array\n");// asks the user for the int k
- scanf("%d",&k);// scans k
- if(k > size || k<1)//if k is bigger than the array size or smaller than 1 the program terminates
- return 1;
- printf("the %dth smallest element is %d",k,smallestElement(arr,size,k));//prints the kth smallest number
- return 0;
- }
- int smallestElement(int arr[],int size,int k) //this function does pretty much what selection sort does
- //except that it does not sort the array, it removes the smallest
- //element from the array until it reaches the kth smallest element
- {
- int index = 0;//declaration and initialization of the index of the smallest element
- for(int i = 0;i < k ;i ++)//loops through the array k times
- {
- index = i;//assigns the smallest
- for(int j = i+1; j < size ; j++)// loops through each element in the array that comes after the ith element
- {
- if(arr[j] < arr[index])//finds the smallest element in the array
- {
- index = j;//saves the index of the smallest element in the array
- }
- }
- if(i == k-1)
- return arr[index];//returns the smallest element in the array if the current iteration is the last iteration
- else
- arr[index] = arr[i];//removes the smallest element from the array
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement