I attempted a quicksort algorithm with a 10 element array but there seems to be a problem. After it is sorted, the second element in the sorted array is always out of order. I am not sure why. Any advice is appreciated.

I am using randomly created numbers. If any other info is required, please let me know. This is my first time on this site so I am unsure of how to properly post things, but here is my code:

nval is not defined on here but it is an integer with value of 10.

void quicksort()

{

int temp;

int i = 0;

int j = nval - 1;

int pivot = x[nval / 2];

while (i <= j)

{

for (i = 0; i < nval - 1; i++)

{

for (j = nval - 1; j > 0; j--)

{

if (x[i] <= x[j])

{

temp = x[i];

x[i] = x[j];

x[j] = temp;

}

}

}

}

I am using randomly created numbers. If any other info is required, please let me know. This is my first time on this site so I am unsure of how to properly post things, but here is my code:

nval is not defined on here but it is an integer with value of 10.

void quicksort()

{

int temp;

int i = 0;

int j = nval - 1;

int pivot = x[nval / 2];

while (i <= j)

{

for (i = 0; i < nval - 1; i++)

{

for (j = nval - 1; j > 0; j--)

{

if (x[i] <= x[j])

{

temp = x[i];

x[i] = x[j];

x[j] = temp;

}

}

}

}

Last edited on

quicksort should be recursive. It looks close but it is missing the recursive call and base case setup, and I am not sure the loops are correct because the recursion will cover some of the looping.

from wiki:

The steps are:

Pick an element, called a pivot, from the array.

Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which are in order by definition, so they never need to be sorted.

post code in <> tags (post format options).

from wiki:

The steps are:

Pick an element, called a pivot, from the array.

Partitioning: reorder the array so that all elements with values less than the pivot come before the pivot, while all elements with values greater than the pivot come after it (equal values can go either way). After this partitioning, the pivot is in its final position. This is called the partition operation.

Recursively apply the above steps to the sub-array of elements with smaller values and separately to the sub-array of elements with greater values.

The base case of the recursion is arrays of size zero or one, which are in order by definition, so they never need to be sorted.

post code in <> tags (post format options).

Last edited on

Topic archived. No new replies allowed.