Quick sort implementation in C

               Quick sort is one of the sorting methods in data structures. The algorithm follows the divide and conquer method.

Logic:

  • First, a pivot element is selected.
  • Check the elements in the array with the pivot element. If the element is less than pivot, it goes to the left of the array.
  • If the element is greater than the array, it goes to the right of the array.
  • This process is repeated until the last element.

Program:

#include <stdio.h>

void fn_swap(int *a, int *b) {

    int temp = *a;

    *a = *b;

    *b = temp;

}

int fn_partition(int arr[], int v_low, int v_high) {

    int pivot = arr[v_high]; // set last element as pivot

    int i = v_low - 1;

    for (int j = v_low; j < v_high; j++) {

        if (arr[j] < pivot) {

            i++;

            fn_swap(&arr[i], &arr[j]);

        }

    }

    fn_swap(&arr[i + 1], &arr[v_high]);

    return i + 1;

}

void quick_Sort(int arr[], int v_low, int v_high) {

    if (v_low < v_high) {

        int pi = fn_partition(arr, v_low, v_high);

        quick_Sort(arr, v_low, pi - 1);

        quick_Sort(arr, pi + 1, v_high);

    }

}

int main() {

    int arr[] = {40, 27, 18, 9, 12, 56, 36};

    int n = sizeof(arr) / sizeof(arr[0]);

    printf("The array elements are:\n");

    for (int i = 0; i < n; i++)

        printf("%d ", arr[i]);

    quick_Sort(arr, 0, n - 1);

    printf("\nThe Sorted array elements are:\n");

    for (int i = 0; i < n; i++)

        printf("%d ", arr[i]);

    return 0;

}

Output:

The array elements are:

40 27 18 9 12 56 36

The Sorted array elements are:

9 12 18 27 36 40 56

This algorithm is efficient one. It has the time complexity of O (n log n). Hope,this code is useful to you. Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.