Why use a pointer to that algorithm?

Asked

Viewed 93 times

1

When I withdraw the code does not work. Why?

And why the algorithm of Insertion Sort is only suitable for list of small entries, type array and list (little)?

 void insert_sort(int *vetor, int TAM){
     int i, j, aux;
     for(i = 1; i < TAM; i++){
         aux = vetor[i];
         for(j = i; (j > 0) && (aux < vetor[j - 1]); j--)
             vetor[j] = vetor[j - 1];
         vetor[j] = aux;
     }
 }
  • 1

    I answered another question, but I shouldn’t, if it’s another question, ask separately.

1 answer

4


You want to sort a sequence of values, right? If you pass one int is only passing a value.

If you create a sequence of values somewhere you can just pass the address of where this sequence is and the algorithm can access these values and do what it needs in each of the elements.

You may be asking why not pass the whole sequence. She’s probably too big to copy everything from one place to another, which has no need to do this.

Has a question that talks about practical use of pointer.

The main problem of the insertion classification algorithm is that it has quadratic complexity (O(n2)) in the worst case. So for only 1000 elements in reverse order it has to do 1 million operations of data copies, this is tragic. But in small volumes this is not impactful and by maintaining reference locale the cache is much more efficient and can be faster than algorithms that make fewer copies but need to compare more or that comparisons cost more, or that need more memory.

  • Clear doubt about the use of the pointer and the complexity. Thanks !

Browser other questions tagged

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