Vector and matrix ordering [closed]

2

Is there another method for ordering array / array in ascending or descending order without being what I used? (What would you change in this code to make it "better"?)

#include <stdio.h>
#include <stdlib.h>

void ordem (int vetor[], int tamanho);

int main ( void ) {

    int tamanho, *vetor;

    printf("\nInforme o tamanho do vetor: ");
    scanf("%i",&tamanho);

    vetor = (int *) malloc(tamanho * sizeof(int));

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

        printf("\nInforme o valor %i: ", i + 1);
        scanf("%i",&vetor[i]);

    }

    ordem (vetor, tamanho);

    puts("\n-----------------------------");

    for ( int p = 0; p < tamanho; p++){
        printf("\n%i ",vetor[p]);
    } puts("");

    free(vetor);

    return 0;
}

void ordem (int vetor[], int tamanho){

    int cache = 0;

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

        for ( int h = i + 1; h < tamanho; h++){

            if (vetor[i] > vetor[h]){

                cache = vetor[i];

                vetor[i] = vetor[h];

                vetor[h] = cache;

            }

        }

    }

}
    
asked by anonymous 25.10.2016 / 16:15

1 answer

3

Search a little about Algorithms . There is no 'most efficient', how good it is depends very much on the vector you are going to order. What you have used is Bubble Sort, it is usually the first ordering algorithm presented to students. An algorithm that is (very) efficient is the Quick Sort , it basically divides the vector recursively, thus making the same organization task more quickly.

    
26.10.2016 / 08:05