I need to choose middle element as pivot. What should I do. I tried changing `pivot`

to `a[mid]`

,

but there’s something I am missing, which I can’t seem to find out.

```
int partition(int a[], int l, int h, int n)
{
int pivot = a[l];
int i = l, j = h;
while (i < j)
{
while (i < n && a[i] <= pivot)i++;
while (j >= 0 && a[j] > pivot)j--;
if (i < j)swap(a[i], a[j]);
}
swap(a[l], a[j]);
return j;
}
void quicksort(int a[], int l, int h, int n)
{
if (l < h)
{
int j = partition(a, l, h, n);
quicksort(a, l, j - 1, n);
quicksort(a, j + 1, h, n);
}
}
```

This code works fine but I’m having issues with the one below:

```
int partition(int a[], int l, int h, int n)
{
int mid = (l + h) / 2;
int pivot = a[mid];
int i = l, j = h;
while (i < mid && j > mid)
{
while (i < mid && a[i] <= pivot)i++;
while (j > mid && a[j] > pivot)j--;
if (i < mid && j > mid)swap(a[i], a[j]);
}
swap(a[mid], a[j]);
return j;
}
void quicksort(int a[], int l, int h, int n)
{
if (l < h)
{
int j = partition(a, l, h, n);
quicksort(a, l, j - 1, n);
quicksort(a, j + 1, h, n);
}
}
```

Any help would be appreciated!