Computer Organization and Design assignements
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

59 lines
1.4 KiB

  1. //============================================================================
  2. // Name : quiz3.cpp
  3. // Author : Christos Choutouridis
  4. // Version :
  5. // Copyright : Your copyright notice
  6. // Description : Hello World in C++, Ansi-style
  7. //============================================================================
  8. int v[] = {
  9. 3, 10, 8, 2, 7, 1, 5, 9, 6, 4
  10. };
  11. void swap (int i, int j) {
  12. int t = v[i];
  13. v[i] = v[j];
  14. v[j] = t;
  15. }
  16. // partition(int f, int l) : permutes the values in vector v[]
  17. // between positions f and l, using as pivot the element v[l], such
  18. // that
  19. // f <= i < p ==> v[i] <= v[p]
  20. // p < i <= l ==> v[p] < v[i]
  21. // The function returns the position p of the pivot.
  22. int partition(int f, int l) {
  23. int pivot = v[l]; // element v[l] is the pivot
  24. int i = f; // i points to the beginning of the vector
  25. // loop over vector
  26. for (int j = f; j < l; j++)
  27. if (v[j] < pivot) // element smaller than pivot
  28. swap(i++,j); // swap it with position pointed by i
  29. swap(i, l ); // swap pivot to its correct position
  30. return (i); // return pivot's position
  31. }
  32. // qsort(int f, int l) : sorts the elements of v[] between positions f:l
  33. void qsort(int f, int l) {
  34. int pivot;
  35. if (f < l) {
  36. pivot = partition(f, l);
  37. qsort(f, pivot - 1); // Before pi
  38. qsort(pivot + 1, l); // After pi
  39. }
  40. }
  41. int main() {
  42. int n = 10;
  43. qsort (0, 9);
  44. return 0;
  45. }