fork download
  1. /*Adobe Elitmus Written Test on 27-10-2013 @Bangalore - Algo/DS questions
  2.  *Question 2
  3.  */
  4.  
  5. /*
  6.  * In a given set of elements(any order), find K largest numbers
  7.  * e.g arr[]={1,4,5,108,10,14,90,43,100} let K=3
  8.  * Ouput = {108,100,90}
  9.  */
  10.  
  11. /*Approach: Modified Bubble Sort
  12.  * As we know that bubble sort in Ith pass places the ith largest number at last
  13.  * After Kth pass, the results will be available and no need to sort further
  14.  */
  15.  
  16. #include<stdio.h>
  17. #include<stdlib.h>
  18.  
  19. //Its Modified Bubble sort
  20. void FindKLargestNumbers(int arr[], int n, int K, int output[])
  21. {
  22. int i,j,count,tmp;
  23.  
  24. for(i=0;i<n;i++)
  25. {
  26. for(j=0;j<n-1;j++)
  27. {
  28. if(arr[j]>arr[j+1])
  29. {
  30. tmp=arr[j];
  31. arr[j]=arr[j+1];
  32. arr[j+1]=tmp;
  33. }
  34. }
  35. if(i==K) break; // K largest numbers are bubbled at top(last indices)
  36. }
  37.  
  38. count=0;
  39. for(i=n-1;i>=n-K;i--)
  40. {
  41. output[count++]=arr[i];
  42. }
  43.  
  44. }
  45.  
  46. void PrintKLargestNuners(int output[] ,int K)
  47. {
  48. int i;
  49.  
  50. printf("The K=%d largest numbers in the given array are\n",K);
  51. for(i=0;i<K;i++)
  52. {
  53. printf("%d ",output[i]);
  54. }
  55. printf("\n");
  56. }
  57.  
  58.  
  59.  
  60. int main()
  61. {
  62. int n=9;//no of elements in the array
  63. int K=3;//largest K numbers
  64. int arr[9]={1,4,5,108,10,14,90,43,100};
  65. int output[3];//output array
  66.  
  67. FindKLargestNumbers(arr,n,K,output);
  68.  
  69. PrintKLargestNuners(output,K);
  70.  
  71. return 0;
  72. }
  73.  
  74.  
Success #stdin #stdout 0s 2248KB
stdin
Standard input is empty
stdout
The K=3 largest numbers in the given array are
108 100 90