Friday, 29 August 2014

C Program for Quick Sorting

 C Source code for implementing Quick Sort using recursive function . This program accepts No. of values to be sorted and the actual values to be sorted from user. By using Quick Sort algorithm it sorts the values and prints the output.

Source Code

/*
    Quick Sorting
    --------------
    Input :
        1. No. of values to be sorted i.e. n.
        2. Values to be sorted. i.e. n values.
    Output:
        List of sorted values.
*/


#include<stdio.h>
#include<conio.h>

void quicksort(int [100], int, int);

int main() {
    int array[100], size, i;

    clrscr();
    printf("Enter size of the array: ");
    scanf("%d", &size);

    printf("Enter %d elements:\n", size);
    for(i=0;i<size;i++)
        scanf("%d", &array[i]);

    // Call the function by passing array, starting index and ending index
    quicksort(array, 0, size-1);

    printf("\n\nArray after sorting:\n");
    for(i=0;i<size;i++)
        printf("%d ", array[i]);

    getch();
    return 0;
}

/*  Function for Quick Sorting */

void quicksort(int array[100], int start_index, int end_index) {
    int pivot,j,temp,i;

    if(start_index<end_index){
        pivot=start_index;
        i=start_index;
        j=end_index;

        while(i < j){
            while(array[i] <= array[pivot] && i < end_index)
                i++;
            while(array[j] > array[pivot])
                j--;

            if(i < j){
                temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
        }

        temp = array[pivot];
        array[pivot] = array[j];
        array[j] = temp;
        quicksort(array,start_index,j - 1);
        quicksort(array,j + 1,end_index);

    }
}



Output
 

No comments:

Post a Comment