-1

I have an algorithm that does the reverse of partition

Reverse-Partition(A, p, q, r)
  pivot = A[q]
  j = r
  i = q
   while j ≥ p + 1 and i ≥ p
     if A[j] > pivot
      exchange A[j] with A[i]
      i = i − 1
   j = j − 1

I am trying to write an algo that is faster than the above one to get the most optimal run time

Fast-Reverse-Partition(A, p, q, r) 
BEGIN:

For(int i = r; i > (r-q); i--):
   swap A[i] and A[i-(r-q)]

END

In Reverse-partition function, in a given array all element in index q~r are all bigger than pivot element and elements in index p~q are all smaller than pivot so i think with above one we can get same result like Reverse-partition function.
This function has runtime n = r-(r-q)+1 = q+1 so it is faster that reverse-partition function.
Does this make sense? or is my understanding wrong?

henryD
  • 21
  • 3
  • When doing work like this it's a good idea to set up a testing framework where you can continuously verify that your algorithm still does what it's supposed to do as you make changes to it. – 500 - Internal Server Error Oct 07 '21 at 11:24

1 Answers1

1

The first function you've provided looks like the partition function from the quicksort algorithm, although I'm not entirely sure that it's correct. But I'll assume that is what you want to replicate.

First of all, your second code snippet is not equivalent to the first one semantically. Second code snippet just blindly reverses the order of the elements of the subarray, that is NOT what partition subroutine should do.

Partition subroutine picks one pivot value from the given subarray and rearranges the elements of the subarray in such a way, so that all elements less than pivot are located before any of the elements that are greater than pivot.

Regarding the "optimal run time". There are numerous partition schemes invented over the time, most of them trying to optimize one of the following:

  • number of comparisons
  • number of swaps
  • behavior in the worst case (all elements are same, or in strict reversed order)
  • readability

When understanding particular partition scheme, it's important to understand what it tries to optimize, and also what invariants it's trying to maintain (and that can be very challenging!).

I'd recommend to start with the thorough reading of the wiki article, it contains several popular partition schemes with the relevant tradeoffs.

Aivean
  • 10,692
  • 25
  • 39