Sunday, August 20, 2023

Quick Sort Algorithm

 #include<stdio.h>

#include<stdlib.h>


int A[50], n;


// CheckFor:  Create new Array 

void CreateArray(){

     

     // CheckFor: Declaration of local variable

     int i = 0;

          

     // LoopFor: Accepet the array elements using random function

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

          A[i] = rand(); 

}


// CheckFor:  Display the Array

void DisplayArray(){


     // CheckFor: Declaration of local variable     

     int i = 0;

     

     // Checkfor: Display the array elements

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

     

     // LoopFor: Display the array elements

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

          printf("%d \t", A[i]); 

}


void QuickSort(int low, int high){

     // CheckFor: Declaration of local variable 

     int pivot, t, i, j;

     

     // CheckFor: Array is empty or not

     if ( low <= high){

          // CheckFor: Initialise the pivot, low and high

          pivot = A[low];

          i = low + 1;

          j = high;

          

          // LoopFor: Move from low to high

          while ( i <= j){

                // LoopFor: Check the condition for low and increases it value

                while ( pivot >= A[i] && i <= high)

                      i++;

                // LoopFor: Check the condition for high and decreases it value

                while ( pivot < A[j] && j >=  low)

                      j--;

                

                // CheckFor: low does not cross the high then swap low and high 

                // position elements into the array

                if ( i < j){

                     t = A[i];

                     A[i] = A[j];

                     A[j] = t;

                }

          }

          // CheckFor: low cross the high then swap pivot and high 

          // position elements into the array

          A[low] = A[j];

          A[j] = pivot;

          

          // After that divide the array from less than pivot and greater than pivot

          QuickSort(low, j-1);

          QuickSort(j+1, high);

     }

}

     

int main(){

    

    printf("How many element we want to enter into Array: ");

    scanf("%d", &n);

    

    CreateArray();

    DisplayArray();

    

    QuickSort(0, n-1);

    printf("\n");

    DisplayArray();

    printf("\n");

    system("pause");

    

    return 0;

}


No comments:

Post a Comment

To Connect Java program with the MYSQL Database

To connect java application with the MYSQL database, first of all to install MYSQL database in your machine. To install MYSQL in your mach...