Pages

Wednesday 25 December 2019

QUICK SORT

// Java program for implementation of QuickSort
class qsrk
{
    static void sort(int a[], int p, int r)
    {
        if (p < r)
        {
            int q = partition(a, p, r);
            sort(a, p, q-1);
            sort(a, q+1, r);
        }
    }
    public static void main(String args[])
    {
        int a[] = {5, 7, 6, 1, 3, 2, 4};
        int n = a.length;
        System.out.printf("\n unsorted array :");
        for (int i=0; i<n; i++)
            System.out.print(a[i]+" ");
       
        sort(a, 0, n-1);

        System.out.printf("\n sorted array :");
        for (int i=0; i<n; i++)
            System.out.print(a[i]+" ");
    }

    static int partition(int a[], int p, int r)
    {
        int pivot = a[r];
        int i = (p-1); // index of smaller element
        for (int j=p; j<=r-1; j++)
        {
            // If current element is smaller than the pivot
            if (a[j] < pivot)
            {
                i++;

                // swap a[i] and a[j]
                int temp = a[i];
                a[i] = a[j];
                a[j] = temp;
                System.out.printf("\n\n exchange a[%d,i]=%d and a[%d,j]=%d ", i,a[j],j,a[i]);
   
            }
        }

        // swap a[i+1] and a[r] (or pivot)
        int temp = a[i+1];
        a[i+1] = a[r];
        a[r] = temp;
        System.out.printf("\n\n exchange a[%d,i+1]=%d and a[%d,r]=%d ", i+1,a[r],r,a[i+1]);
        return i+1;
    }

}

output:





No comments:

Post a Comment

Constructors & Destructors in c++

  Constructors :  A Constructor is a special member function, which is used to initialize the objects of its class. The Constructor is invok...