Vejamos agora um exemplo de implementação desse método de ordenação em java:

Exemplo 1_3_4: exemplo de busca bubbleSort.

public class BubbleSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] valores = {1,2,7,15,35,41,42,48,49,50,51,58,59,60,63,65};
        bubbleSort(valores);
        for(int i=0; i<valores.length;i++){
            System.out.println(valores[i]);
        }
        
    }
    public static void bubbleSort(int[] number) {
        int temp, bottom;
        boolean exchanged = true;
        bottom = number.length - 2;
        while (exchanged) {
            exchanged = false;
            for (int i = 0; i <= bottom; i++) {
                if (number[i] > number[i+1]) {
                    temp = number[i]; //exchange
                    number[i] = number[i+1];
                    number[i+1] = temp;
                    exchanged = true; //exchange is made
                }
            }
//        assert maxBottom(number, bottom):
//        "Error: " + number[bottom] +
//        " at position " + bottom +
//        " is not the largest.";
//        bottom--;
        }
//        assert isSorted(number):
//        "Error: the final is not sorted";
    }
    private static boolean maxBottom(int[] number, int lastIndex) {
        for (int i = 0; i < lastIndex; i++) {
            if (number[lastIndex] < number[i]) {
                return false;
            }
        }
        return true;
    }
    private boolean isSorted(int[] number) {
        for (int i = 0; i < number.length-1; i++) {
                if (number[i] > number[i+1]) {
                    return false;
                }
        }
        return true;
    }
}

Esse método de pesquisa binária também fará aproximadamente N2 comparações. O método a seguir é mais eficiente.

Copyright © 2014 AIEC.