Advertisement
Guest User

Untitled

a guest
Jul 20th, 2017
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. //This program recursively sorts an array
  2.  
  3. #include<stdio.h>
  4.  
  5. void rec_sort(int values[], int n);
  6.  
  7. main()
  8. {
  9. int vals[4];
  10. vals[0] = 37; vals[1] = 48; vals[2] = 56; vals[3] = 63;
  11. printf("this array sorted: %x\n", rec_sort(vals[], 4));
  12.  
  13. system("Pause");
  14. return 0;
  15. }
  16.  
  17. void rec_sort(int values[], int n) {
  18. //Base case
  19. if (n<2) return;
  20.  
  21. int maxIndex=0;
  22. int i;
  23.  
  24. //Find max item in array in indexes 0 through n-1
  25. for(i=1; i<n;i++) {
  26. if(values[i] > values[maxIndex])
  27. maxIndex=i;
  28.  
  29. }
  30.  
  31. //Swap this element with one stored in n-1
  32. //Set temp to n-1, set n-1 in array to max, set max to temp
  33. int temp = values[n-1]; //Store temp as last element in array
  34. values[n-1] = values[maxIndex]; //Store last element as max value in array
  35. values[maxIndex] = temp; //temp will keep on changing, as array is sorted
  36.  
  37. //Recursively sort the array values of length n-1
  38. sort(values, n-1);
  39.  
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement