0
2.8kviews
Write a program in C to perfrom Quick sort. Show steps with example
1 Answer
0
63views
  1. Program for Quick Sort

    #include<stdio.h> 
    #include<conio.h>
    void swap(int* a, int* b)
    {
        int t = *a;
        *a = *b;
        *b = t;
    }
    
    int partition (int arr[], int low, int high)
    {
        int pivot = arr[high]; // pivot
        int i = (low - 1); // Index of smaller element
        int j;
        for (j = low; j <= high- 1; j++)
        {
            // If current element is smaller than or
            // equal to pivot
            if (arr[j] <= pivot)
            {
                i++; // increment index of smaller element
                swap(&arr[i], &arr[j]);
            }
        }
        swap(&arr[i + 1], &arr[high]);
        return (i + 1);
    }
    void quickSort(int arr[], int low, int high)
    {
        if (low < high)
        {
            int pi = partition(arr, low, high);
            quickSort(arr, low, pi - 1);
            quickSort(arr, pi + 1, high);
        }
    }
    void printArray(int arr[], int size)
    {
        int i;
        for (i=0; i < size; i++)
            printf("%d ", arr[i]);
        printf("\n");
    }
    void main()
    {
        int arr[] = {4, 7, 8, 9, 1, 5};
        int n = sizeof(arr)/sizeof(arr[0]);
        clrscr();
        printf("Unsorted array: \n");
        printArray(arr, n);
        quickSort(arr, 0, n-1);
        printf("\nSorted array: \n");
        printArray(arr, n);
        getch();
    }
    
  2. Step by Step Example for Quick Sort a. Consider the unsorted values {25, 13, 7, 34, 56, 23, 13, 96, 14, 2} with first element as pivot element i.e 25 is pivot

enter image description here

b. Hence after quick sort the sorted array becomes 2, 07, 13, 13, 14, 23, 25, 34, 56, 96

Please log in to add an answer.