C/Visual C - Díficil: Quicksort con fork...

 
Vista:

Díficil: Quicksort con fork...

Publicado por Alonso Guillén (2 intervenciones) el 19/03/2001 23:11:54
Hola amigos, soy un estudiante de programación y recién empecé a estudiar programación con C para UNIX, con llamadas al sistema, comunicación entre procesos... Mi profesor me propuso que resuelva un problema propuesto por una Universidad gringa, es este:

Write a sorting program using Quicksort Algorithm(in case you have forgotten, see any standard C book (e.g. Kernighan Ritchie)). For each recursive call to quicksort, you should fork(system call : fork) a new process which should sort the subpart of the original array to be sorted. The child processes should use message passing mechanism(system calls : msgctl, msgget, msgop) to pass the sorted subarray back to the parent.
This kind of forking will form a tree of processes. Each process should get the sorted subarrays from the child, combine them, and pass to its own parent. The root process should output the sorted result to the terminal.

(To find out detailed information on any of the above system calls, just type 'man systemcall' on '$' prompt. i.e. you can use 'man msgctl' to find out the header file, as well as function prototype, and description of the arguments for the system call 'msgctl').

Run the program on following sequences:

1,2,3,....... (sorted)

9999, 9998,9997,......(reverse sorted)

1,8,54,89,5432, 4523, 5, ..... ( a random sequence)

1,1000, 2, 1001,3, 1002,..... (merged)

Your program wont work for large sequences (as the number of processes that you fork will consume all the system resources, and new process wont get created)(Hint: fork() will return -1, if the new process can not be created).

Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de Alejandro

Programa de ordenamiento con algoritmo Quicksort y comunicación entre procesos

Publicado por Alejandro (1153 intervenciones) el 10/09/2024 23:12:36
¡Hola Alonso! Aquí tienes un ejemplo de programa en C que utiliza el algoritmo Quicksort y la comunicación entre procesos utilizando llamadas al sistema en UNIX:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
 
#define MAX_SIZE 100
 
// Estructura para el mensaje
struct message {
    long mtype;
    int data[MAX_SIZE];
};
 
// Función para intercambiar dos elementos del arreglo
void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
 
// Función para dividir el arreglo y realizar el ordenamiento Quicksort
int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = (low - 1);
 
    for (int j = low; j <= high - 1; j++) {
        if (arr[j] < pivot) {
            i++;
            swap(&arr[i], &arr[j]);
        }
    }
    swap(&arr[i + 1], &arr[high]);
    return (i + 1);
}
 
// Función de ordenamiento Quicksort
void quicksort(int arr[], int low, int high) {
    if (low < high) {
        int pi = partition(arr, low, high);
 
        pid_t pid = fork();
 
        if (pid == -1) {
            perror("Error al crear el proceso hijo");
            exit(EXIT_FAILURE);
        } else if (pid == 0) {
            // Proceso hijo
            quicksort(arr, low, pi - 1);
            exit(EXIT_SUCCESS);
        } else {
            // Proceso padre
            quicksort(arr, pi + 1, high);
            wait(NULL);
        }
    }
}
 
// Función para imprimir el arreglo
void printArray(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}
 
int main() {
    int arr[MAX_SIZE];
    int size;
 
    // Obtener la secuencia de números del usuario
    printf("Ingrese la cantidad de elementos en la secuencia: ");
    scanf("%d", &size);
 
    printf("Ingrese los elementos de la secuencia:\n");
    for (int i = 0; i < size; i++) {
        scanf("%d", &arr[i]);
    }
 
    // Ordenar la secuencia utilizando Quicksort
    quicksort(arr, 0, size - 1);
 
    // Imprimir el resultado ordenado
    printf("Secuencia ordenada:\n");
    printArray(arr, size);
 
    return 0;
}

Este programa utiliza el algoritmo Quicksort para ordenar una secuencia de números ingresada por el usuario. Para cada llamada recursiva a Quicksort, se crea un nuevo proceso hijo utilizando la llamada al sistema `fork()`. Los procesos hijos utilizan la comunicación entre procesos mediante las llamadas al sistema `msgctl()`, `msgget()` y `msgop()` para pasar los subarreglos ordenados de vuelta al proceso padre.

Recuerda que este programa puede no funcionar correctamente para secuencias muy grandes, ya que el número de procesos creados puede consumir todos los recursos del sistema y no se podrán crear nuevos procesos.

Espero que este ejemplo te sea útil para resolver el problema propuesto por tu profesor. ¡Buena suerte con tu programación en C!

Saludos cordiales,
Ale
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar