Code Scrappers


Quick Sort C Program


                    #include<stdio.h>
                    #include<stdlib.h>

                    void main()

                    {
                            int n, i, a[10];

                            printf("enter the size of array\n");

                            scanf("%d",&n);

                            printf("enter the array elements\n");

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

                            {
                                    scanf("%d",&a[i]);
                            }

                            quicksort(a, 0, n-1);

                            printf("array after sorting is");

                            for(i=0;i<n;i++)
                            {
                                    printf("\n%d",a[i]);
                            }

                    }

                    void quicksort(int a[], int first, int last)

                    {
                            int j;

                            if(first >= last)
                            {
                                    return;
                            }

                            else
                            {
                                    j = partition(a, first, last);

                                    quicksort(a, first, j-1);

                                    quicksort(a, j+1, last);
                            }
                    }
                    int partition(int a[], int first, int last)

                    {
                            int i, j, pivot, temp;

                            i = first;

                            j = last;

                            pivot = first;

                            while(i < j)
                            {
                                    while(a[i] < a[pivot])
                                    {
                                            i++;
                                    }

                                    while(a[j] > a[pivot])
                                    {
                                            j--;
                                    }


                                    if(a[i] > a[j])
                                    {
                                          temp = a[i];

                                          a[i] = a[j];

                                          a[j] = temp;
                                    }
                            }

                            temp = a[pivot];

                            a[pivot] = a[j];

                            a[j] = temp;

                            return j;
                    }


                



Output

            enter the size of the array
            5
            enter the array elements
            1
            4
            2
            8
            7
            array after sorting is
            1
            2
            4
            7
            8