BubbleSort算法返回不希望的结果

时间:2017-01-06 18:05:30

标签: java bubble-sort

这是我对冒泡排序算法的实现。

[1, 3, 5, 6, 2]
[1, 6, 5, 3, 2]

这是输出:

\bD:(\S+)

这显然是错的,但我的逻辑似乎还不错。

4 个答案:

答案 0 :(得分:3)

你的两个问题都在这一行:

for (j = 1; j < unsorted.length-1; j++) {

你不想从第一个元素循环,你想在i之后从第一个元素循环:

for (j = i+1; j < unsorted.length-1; j++) {

你还需要一直走到最后:

for (j = i+1; j < unsorted.length; j++) {

答案 1 :(得分:1)

一些事情 1)您可以在循环范围内声明i和j 2)尝试在迭代0 - >中保持一致。长度 3)少于登录i&lt; unsorted.length将确保您不会超过索引边界。因为数组索引的范围从0到length-1。 4)您的交换逻辑很棒,唯一需要注意的是循环范围。 5)未分类[i]&lt;未分类[j]将决定订单的去向。

public static void bubbleSort(int[] unsorted) {
    for (int i = 0; i < unsorted.length; i++) {
        for (int j = 0; j < unsorted.length; j++) {
            if (unsorted[i] < unsorted[j]) {
                int temp = unsorted[i];
                unsorted[i] = unsorted[j];
                unsorted[j] = temp;
            }
        }
    }
}

答案 2 :(得分:0)

here is the correct code

> import java.util.Arrays;

 public class BubbleSort {
    public static void main(String[] args) {
        int[] unsorted = {1,3,5,6,2};
        System.out.println(Arrays.toString(unsorted));
        bubbleSort(unsorted);
        System.out.println(Arrays.toString(unsorted));
    }

    public static void bubbleSort(int[] unsorted){
        int i;
        int j;
        int temp;
        for (i = 0; i < unsorted.length-1; i++) {
            for (j = i+1; j < unsorted.length; j++) {
                if (unsorted[i] > unsorted[j]) {
                    temp = unsorted[i];
                    unsorted[i] = unsorted[j];
                   unsorted[j] = temp;
                 }
             }
        }
   }
 }

the second loop begins after i so j alway start at i+1 and end at unsorted.length while i end at unsorted.length-1

here is the result I got when I ran this code

答案 3 :(得分:0)

我在计算机中保存了冒泡排序算法,这是(没有复制到新数组):

public static void bubbleSort (int[] v) {
      for (int i=0; i<v.length-1; i++)
         for (int j=v.length-1; j>i; j--)
            if (v[j-1]>v[j]) {
               int aux = v[j-1];
               v[j-1] = v[j];
               v[j] = aux;   
            }
   }