Sort numeric vector without using Bubble Sort

Asked

Viewed 1,218 times

9

We usually learn in college that, to sort integer vectors, we use a technique called Bubble Sort:

int[] vetorOrdenado = new int[8];

    vetorOrdenado[0] = 2;
    vetorOrdenado[1] = 41;
    vetorOrdenado[2] = 12;
    vetorOrdenado[3] = 6;
    vetorOrdenado[4] = 5;
    vetorOrdenado[5] = 29;
    vetorOrdenado[6] = 17;
    vetorOrdenado[7] = 3;

    for(int i = 0; i < vetorOrdenado.length;i++){
        for(int j = 0; j < vetorOrdenado.length - 1; j++){
            if(vetorOrdenado[i] < vetorOrdenado[j]){
                int aux = vetorOrdenado[i];
                vetorOrdenado[i] = vetorOrdenado[j];
                vetorOrdenado[j] = aux; 
            }

        }
    }

This technique sorts an integer vector, as can be seen in ideone.

There is another way to sort numerical vectors without using loop within loop, as in Bubble Sort? Collections has no way to sort an array like this?

  • It has several https://en.wikipedia.org/wiki/Sorting_algorithm http://www.sorting-algorithms.com/ In most cases, well optimized Quick Sort works best. Bubble is very bad. Java has a very suitable algorithm ready: http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#Sort-byte:A-

  • @bigown these methods there are only version 8? I realized that has no return, so he orders taking advantage of the vector itself past?

  • 1

    They are very old. They ordain in-place.

  • Book tip to learn more about sorting algorithms: Algorithms. Theory and Practice - Thomas Cormen

1 answer

5


The most commonly used sorting algorithm is the Quicksort. It is not good for all cases, but it is good in many and the most common. Unless you need extreme performance and know that the typical data pattern is better suited for other algorithms is it that should be chosen.

Java that is not silly uses it for a long time in a specific optimization to increase the number of cases where it is suitable. This is available on the API of array.

For cases where a collection needs to be analyzed against itself, all it doesn’t want is a complexity O(N2), which is common in this case. And the QS allows in most cases O(N logN), which is the best one can expect in the general case.

The Radix may be even better, but it is difficult to implement it.

Comparison of algorithms.

Browser other questions tagged

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