Sort numeric vector without using Bubble sort

8

We usually learn in college that to sort entire 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 a vector of integers, as can be seen in the ideone .

Is there another way to sort numeric vectors without using a loop inside a loop, such as bubble sort ? Collections does not have any way to sort a vector that way?

    
asked by anonymous 27.01.2016 / 02:20

1 answer

4

The most commonly used sorting algorithm is triggered by Quick-sort . It is not good for all cases, but it is good in many and the most common. Unless you need extreme performance and you know that the typical data pattern fits best for other algorithms, it should be chosen.

Java that is not silly has long used it in a specific optimization to increase the number of cases where it is appropriate. This is available at the array array .

For cases where a collection needs to be parsed against itself, all that is not wanted is a complexity O (N 2 ), which is common in this case. And QS allows in most cases O (N logN), which is the best you can expect in the general case.

The Radix might be even better, but it's hard to implement.

Algorithm Comparison .

    
27.01.2016 / 03:14