diff --git a/Arquivos/QuickSort.c b/Arquivos/QuickSort.c index 160f34905529c26d0599dca81807d584fb0fd475..ea70037e2bd1d21181479a233dcc63d6492a42b3 100644 --- a/Arquivos/QuickSort.c +++ b/Arquivos/QuickSort.c @@ -14,30 +14,56 @@ void printVetor( int Vetor[], int n ) { printf( "%d ", Vetor[i] ); printf ("\n"); } -int Mediana (int Esquerda, int Meio, int Direita) { - if ((Esquerda >= Direita && Esquerda <= Meio) || (Esquerda >= Meio && Esquerda <= Direita)) - return Esquerda; - if (( Direita >= Esquerda && Direita <= Meio) || (Direita >= Meio && Direita <= Esquerda)) - return Direita; - else - return Meio; + +int Mediana(int *Vetor, int esq, int dir) { + int aux; + aux = (dir+esq)/2; // elem. do meio do vetor + + //mediana dos 3 numeros + + if ( (Vetor[esq] >= Vetor[aux]) && (Vetor[esq] <= Vetor[dir]) ) + return esq; + + else if ( (Vetor[esq] >= Vetor[dir]) && (Vetor[esq] <= Vetor[aux]) ) + return esq; + + else if ( (Vetor[dir] >= Vetor[aux]) && (Vetor[dir] <= Vetor[esq]) ) + return dir; + + else if ( (Vetor[dir] >= Vetor[esq]) && (Vetor[dir] <= Vetor[aux]) ) + return dir; + + else if ( (Vetor[aux] >= Vetor[esq]) && (Vetor[aux] <= Vetor[dir]) ) + return aux; + + else if ( (Vetor[aux] >= Vetor[dir]) && (Vetor[aux] <= Vetor[esq]) ) + return aux; + } -int Particao (int Vetor[], int Esquerda, int Direita) { - int Pivo, i, j; - - Pivo = Vetor[Direita]; - i = (Esquerda - 1); - for (j = Esquerda; j <= Direita- 1; j++) - { - if (Vetor[j] <= Pivo) - { - i++; - Troca (Vetor, i, j); - } - } - Troca (Vetor,i + 1, Direita); - return (i+1); +int Particao (int *Vetor, int esq, int dir) { + int i,j,pivo,aux; + aux = Mediana(Vetor,esq,dir); + pivo = Vetor[aux]; + printf("%d\n",pivo); + i = esq; + j = dir; + while (i < j) { + + while ( (Vetor[i] <= pivo) && (i < dir) ) + i++; + + while (Vetor[j] > pivo) + j--; + + if (i < j) + Troca(Vetor,j,i); + } + + printVetor(Vetor,18); + Vetor[esq] = Vetor[j]; + Vetor[j] = pivo; + return j; } void QuickSortRecursivo (int Vetor[], int Esquerda, int Direita) { @@ -79,8 +105,9 @@ void QuickSortIterativo (int Vetor[], int Esquerda, int Direita) { } int main() { - int Vetor[] = {51, 2, 45, 95, 43, 78, 12, 32}; + int Vetor[] = {1,2,3,4,5,8,6,4,43,43,56,23,43,4,3,75,342,532}; int n = sizeof( Vetor ) / sizeof( *Vetor ); - QuickSortRecursivo( Vetor, 0, n - 1 ); + printVetor (Vetor, n); + QuickSortIterativo( Vetor, 0, n - 1 ); printVetor( Vetor, n ); }