Hello, I am very new to C and having the hardest time with arrays. I am attempting to find a pivot point in a sorted array for example { 1 2 4 5 9 } might become { 5 9 1 2 4 }. I am thinking it should be something to the degree of start at array[size] and if it is larger than array[size-1] continue if not array[size] is the pivot point. I could be completely off in that assumption but regardless I am having problems coding it either way. Could anyone shed some light on this for me or let me know if I am completely off target.

``````#include<stdio.h>
#define size 5
int main(void)
{
int array[size] = {4, 8, 0, 1, 3};
int prev = array[size-1];
int last;
int pivot;

for (last = array[size]; last >= prev; prev--)
``````
3
Contributors
3
Replies
4
Views
5 Years
Discussion Span
Last Post by deceptikon

any thoughts?

for example { 1 2 4 5 9 } might become { 5 9 1 2 4 }.

Can you be more specific as to how this will happen ?

As for pivoting, google for quick sort and there you will find your pivoting method.

I am attempting to find a pivot point in a sorted array for example { 1 2 4 5 9 } might become { 5 9 1 2 4 }.

That seems simple enough. The array is already sorted, so just start swapping everything from the median:

``````for (int i = 0, j = median; j < n; ++i, ++j)
swap(&a[i], &a[j]);
``````

This works perfectly for even numbered arrays, but for odd numbered arrays the median itself is an outlier. The swap trick from above will work for all but the median, but then you can shift the right half of the array one spot to the left and plug the median in at the end to finish things up:

``````int save = a[median];

for (int i = 0, j = median + 1; j < n; ++i, ++j)
swap(&a[i], &a[j]);

memmove(&a[median], &a[median + 1], (n - median - 1) * sizeof *a);
a[n - 1] = save;
``````

Easy peasy. :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.