Vector and matrix ordering

Asked

Viewed 396 times

2

Do you have another method to sort vector/matrix in ascending or descending order other than the one 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;

            }

        }

    }

}
  • 2

    The problem is precisely that there are numerous. TAKE A LOOK AT [Ask].

1 answer

2


Research a little about Sorting algorithms. There is no 'more efficient', how good it is depends a lot on the vector you will sort. What you used is Bubble Sort, 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 organizing task faster.

  • Vlw, I’ll do a little research.

  • 2

    Just an addendum, take a look at the function qsort of stdlib.h. This is a standard implementation of Quick Sort, not by far the fastest possible implementation, but is robust and easy to use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.