Advertisement
Guest User

Untitled

a guest
Sep 20th, 2014
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.21 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <math.h>
  4. int counter = 0;
  5. int findNth(int* set, int setSize, int n)
  6. {  
  7.     if(n == 0)
  8.         return set[setSize];
  9.        
  10.     int i, z, temp;
  11.     int max = set[setSize - 1];
  12.     int swapTo = setSize - 1;
  13.  
  14.     printf(".[ ");
  15.     for(z = 0; z < setSize; z++)
  16.         printf("%i ",set[z]);
  17.     printf("] (recursion)\n");
  18.  
  19.     for(i = 0; i < setSize; i++)
  20.     {
  21.         while(set[i] > max)
  22.         {
  23.             max = set[i];
  24.            
  25.             set[i] = set[swapTo];
  26.             set[swapTo] = max;
  27.            
  28.             swapTo--;
  29.            
  30.             printf("..[ ");
  31.             for(z = 0; z < setSize; z++)
  32.                 printf("%i ",set[z]);
  33.             printf("] (swap)\n");
  34.             counter++;
  35.         }
  36.     }
  37.     counter += setSize;
  38.     if(swapTo == setSize - 1)
  39.         return findNth(set,swapTo,n - 1);
  40.     if(swapTo + n >= setSize)
  41.         return findNth(set,swapTo + 1,n + swapTo + 1 - setSize);
  42.        
  43.     return set[swapTo + n];
  44. }
  45.  
  46.  
  47. main()
  48. {
  49.     int test[] = {3, 2, 8, 5, 1, 9, 2, 66, 4, 9};
  50.    
  51.     printf("5th Largest: %i\n",findNth(test,sizeof(test)/sizeof(int),5));
  52.     printf("Comaprisons: %i",counter);
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement