Practical 7 by Karan

 // Quick sort in C


#include <stdio.h>

#include <stdlib.h>

#include <string.h>


 struct student {

char name[20];

int rollno;

int mark;


} ;


// function to find the partition position

int partition(struct student array[], int low, int high) {

  

  // select the rightmost element as pivot

  int pivot = array[high].rollno;

  

  // pointer for greater element

  int i = (low - 1);


  // traverse each element of the array

  // compare them with the pivot

  for (int j = low; j < high; j++) {

    if (array[j].rollno<= pivot) {

        

      // if element smaller than pivot is found

      // swap it with the greater element pointed by i

      i++;

      

      // swap element at i with element at j

     

    struct student temp ;

     temp = array[i];

      array[i] = array[j];

  array[j] = temp ;

    }

  }

   // swap the pivot element with the greater element at i

  struct student temp ;

     temp = array[i+1];

      array[i+1] = array[high];

  array[high] = temp ;

 


  

  // return the partition point

  return (i + 1);

}


void quickSort(struct student array[], int low, int high) {

  if (low < high) {

    

  

    int pi = partition(array, low, high);

    

    // recursive call on the left of pivot

    quickSort(array, low, pi - 1);

    

    // recursive call on the right of pivot

    quickSort(array, pi + 1, high);

  }

}


// function to print array elements

void printArray(struct student array[], int size) {

  for (int i = 0; i < size; ++i) {

     printf("name = %s",array[i].name);

    printf(" roll no = %d ", array[i].rollno);

     printf(" marks = %d ", array[i].mark);

    printf("\n");

  }

  printf("\n");

}


// main function

int main() {

  int no , i ;

  printf("enter no of studets\n");

  scanf("%d", &no);



  struct student data[no] ;


  for(i=0;i<no;i++){   

    printf("\nEnter Name of student %d:", (i+1));    

scanf("%s",&data[i].name);


printf("Enter Rollno:");    

scanf("%d",&data[i].rollno);    

 

printf("Enter marks:");    

scanf("%d",&data[i].mark);    

}    


  int n = sizeof(data) / sizeof(data[0]);

  printf("no of data is %d\n",n);

  printf("Unsorted Array\n");

  printArray(data, n);

  

  // perform quicksort on data

  quickSort(data, 0, n - 1);

  

  printf("Sorted array in ascending order: \n");

  printArray(data, n);

}

Comments

Popular posts from this blog

DAA P4 bfs, dfs

DAA P8 graph coloring

Practical 8 by Karan