quicksort (personal)

 #include <stdio.h>


struct Student
{
   
    char student_name[50];
    int student_roll_no;
    int total_marks;
};

void swap(struct Student *a, struct Student *b)
{
    struct Student t = *a;
    *a = *b;
    *b = t;
}

int count = 1;

int partition(struct Student arr[], int low, int high)
{
    int pivot = arr[high].student_roll_no;
    int i = (low - 1);
    for (int j = low; j <= high - 1; j++)
    {
        if (arr[j].student_roll_no < pivot)
        {
            i++;
            swap(&arr[i], &arr[j]);
            count++;
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}

void quickSort(struct Student arr[], int low, int high)
{
    if (low < high)
    {
        int pi = partition(arr, low, high);
        quickSort(arr, low, pi - 1);
        quickSort(arr, pi + 1, high);
    }
}

void printArray(struct Student arr[], int size)
{
    int i;
    for (i = 0; i < size; i++)
    {
        printf("%s \t%d \t%d\n", arr[i].student_name, arr[i].student_roll_no, arr[i].total_marks);
    }
}

int main()
{
    int n, i;
    printf("Enter number of students: ");
    scanf("%d", &n);
    struct Student stud[n];
    fflush(stdin);
    printf("Enter information: ");
   
    for (i = 0; i < n; i++)
    {
        printf("student %d:\nName:", i + 1);
        scanf("%s", stud[i].student_name);
        while (getchar() != '\n');
        printf("Roll no: ");
        scanf("%d", &stud[i].student_roll_no);
        printf(" total Marks: ");
        scanf("%d", &stud[i].total_marks);
    }

    quickSort(stud, 0, n - 1);
    printf("Sorted array: \n");
    printArray(stud, n);
    printf("Number of swap performed is %d", count);

    return 0;
}


Comments

Popular posts from this blog

DAA P4 bfs, dfs

DAA P8 graph coloring

Practical 8 by Karan