PDA

View Full Version : [c]ordinamento crescente righe matrice


mikael_c
12-02-2014, 10:57
come posso fare ad ordinare le righe di una matrice m[i][j] con una procedura tipo merge-sort nel modo più semplice possibile in c?

bancodeipugni
12-02-2014, 11:38
#include <stdlib.h>
#include <stdio.h>

#define MAX 300


/*
* Legge in input il numero n ed n numeri interi
* che memorizza nell'array. Restituisce il numero
* di elementi letti (n).
*/

int leggi_array(int V[]) {
int n, i;

printf("Numero di elementi: ");
scanf("%d", &n);
for (i=0; i<n; i++)
scanf("%d", &V[i]);
return(n);
}


/*
* Stampa in output l'array.
*/

void stampa_array(int V[], int n) {
int i;

for (i=0; i<n; i++) {
printf("%d ", V[i]);
}
printf("\n");
return;
}

/*
* Funzione Merge per la fusione di due
* componenti ordinate dell'array.
*/

void Merge(int A[], int p, int q, int r) {
int i, j, k, B[MAX];

i = p;
j = q+1;
k = 0;
while (i<=q && j<=r) {
if (A[i]<A[j]) {
B[k] = A[i];
i++;
} else {
B[k] = A[j];
j++;
}
k++;
}
while (i<=q) {
B[k] = A[i];
i++;
k++;
}
while (j<=r) {
B[k] = A[j];
j++;
k++;
}
for (k=p; k<=r; k++)
A[k] = B[k-p];
return;
}


/*
* Funzione ricorsiva MergeSort.
*/

void MergeSort(int A[], int p, int r) {
int q;

if (p<r) {
q = (p+r)/2;
MergeSort(A, p, q);
MergeSort(A, q+1, r);
Merge(A, p, q, r);
}
return;
}


/*
* Funzione principale
*/

int main(void) {
int n, V[MAX];

n = leggi_array(V);
MergeSort(V, 0, n-1);
stampa_array(V, n);
return(1);
}

mikael_c
13-02-2014, 09:48
questo è l'algoritmo merge sort, però come si modifica in modo da utilizzarlo su una matrice bidimensionale m[i][j] in modo da ordinare gli elementi delle righe della matrice in ordine crescente??

bancodeipugni
13-02-2014, 15:18
tu vorresti proprio l'insalata anche condita pure ? :D

non si possono fare gli esercizi per intero: devi fare un piccolo sforzo (veramente assai piccolo in questo caso)

Hardware Upgrade Forum Database Error
Database Error Database error
The Hardware Upgrade Forum database has encountered a problem.

Please try the following:
  • Load the page again by clicking the Refresh button in your web browser.
  • Open the www.hwupgrade.it home page, then try to open another page.
  • Click the Back button to try another link.
The www.hwupgrade.it forum technical staff have been notified of the error, though you may contact them if the problem persists.
 
We apologise for any inconvenience.