Search code examples
arrayscsortingquicksortswap

Swap is not done between 2 integers in array in C language


I'm implementing Quick Sort Algorithm in C language, in which at only one particular interchange of 2 values arr[i] and pivot is not being done properly, else all the swapping is done accurately, I have debugged too and tried to understand what is the problem/mistake, maybe it is a logical error.

Here's the code:

#include <stdio.h>
void printArr(int arr[], int n)
{
    for (int i = 0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}

void swap(int *a, int *b)
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

void quickSort(int arr[], int low, int high)
{
    int pvt = arr[high];
    int i = low;
    int j = high;

    while (i < j)
    {
        while (pvt > arr[i])
            i++;
        while (pvt <= arr[j])
            j--;

        if (i < j)
            swap(&arr[i], &arr[j]);
    }
    swap(&arr[i], &pvt);
    printArr(arr, high + 1);
}

void main()
{
    int arr[] = {10, 16, 8, 12, 15, 6, 3, 9, 5};
    int n = sizeof(arr) / sizeof(arr[0]);

    quickSort(arr, 0, n - 1);
}

Solution

  • Just after 2-3 minutes, a friend of mine helped me out, that the pivot is not present in the array so with what I'm swapping it with arr[i]? Instead I can swap 2 values for the same result, arr[i] and arr[high]. Got my mistake :P