Advertisement
Guest User

Untitled

a guest
Sep 26th, 2017
57
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. Choose a pivot value p from anArray[first..last]
  2. Partition the values of anArray[first..last] about p
  3.  
  4. Implement the algorithm kSmall, discussed in the class (Chapter 2, Section 2.4.4), as a C++ function. Use the first value of the array as the pivot.
  5. Requirements:
  6. For the function, the array parameter MUST BE passed as a pointer.
  7. Write a main program to test your function.The array that is to be passed to the function is required to be generated as a dynamic array using new operator
  8.  
  9. #include <iostream>
  10. using namespace std;
  11.  
  12. int kSmall(int k, int *arrayPtr, int first, int last)
  13. {
  14. int pivotIndex = 0;
  15. int p = arrayPtr[pivotIndex];
  16.  
  17. if (k < pivotIndex - first + 1) {
  18. return kSmall(k, arrayPtr, first, pivotIndex - 1);
  19. }
  20. else if (k == pivotIndex - first + 1) {
  21. return p;
  22. }
  23. else {
  24. return kSmall(k - (pivotIndex - first + 1), arrayPtr,
  25. pivotIndex + 1, last);
  26. }
  27. }
  28.  
  29. int main()
  30. {
  31. const int SIZE = 5;
  32. int array[SIZE] = {8,5,3,1,7};
  33. int* arrayPtr = new int[SIZE];
  34. arrayPtr = array;
  35. cout << kSmall(3, arrayPtr, 8, 7) << endl;
  36.  
  37. delete arrayPtr;
  38.  
  39. return 0;
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement