Advertisement
What_Ever

Untitled

Dec 30th, 2015
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.10 KB | None | 0 0
  1. #include <stdio.h>
  2. /*
  3.     A function that takes an array and an integer K,
  4.     and returns the Kth smallest integer in the array
  5. */
  6. int smallestElement(int arr[],int size,int k);
  7. int main()
  8. {
  9.     int size,k;
  10.     printf("Enter the size of the array: ");//asks the user for the size of the array
  11.     scanf("%d",&size);// gets the size from the user
  12.     int arr[size];// the declaration of the array
  13.     printf("Enter the elements of the array\n");//asks the user for the elements of the array
  14.     for(int i = 0; i< size ;i++)
  15.     {
  16.         scanf("%d",&arr[i]);// scanning the elements of the array 1 at a time
  17.     }
  18.     printf("Enter a number K to get the Kth smallest element in the array\n");// asks the user for the int k
  19.     scanf("%d",&k);// scans k
  20.  
  21.     if(k > size || k<1)//if k is bigger than the array size or smaller than 1 the program terminates
  22.         return 1;
  23.  
  24.     printf("the %dth smallest element is %d",k,smallestElement(arr,size,k));//prints the kth smallest number
  25.     return 0;
  26. }
  27.  
  28. int smallestElement(int arr[],int size,int k)   //this function does pretty much what selection sort does
  29.                                                 //except that it does not sort the array, it removes the smallest
  30.                                                 //element from the array until it reaches the kth smallest element
  31. {
  32.     int index = 0;//declaration and initialization of the index of the smallest element
  33.     for(int i = 0;i < k ;i ++)//loops through the array k times
  34.     {
  35.         index = i;//assigns the smallest
  36.         for(int j = i+1; j < size ; j++)// loops through each element in the array that comes after the ith element
  37.         {
  38.             if(arr[j] < arr[index])//finds the smallest element in the array
  39.             {
  40.                 index = j;//saves the index of the smallest element in the array
  41.             }
  42.         }
  43.         if(i == k-1)
  44.             return arr[index];//returns the smallest element in the array if the current iteration is the last iteration
  45.         else
  46.             arr[index] = arr[i];//removes the smallest element from the array
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement