我的冒泡排序算法不对数组进行排序

时间:2017-04-06 06:42:05

标签: java arrays algorithm sorting bubble-sort

这是我的代码:

import java.util.Scanner;
public class BubbleSort{
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int[] array = new int[5];
        for(int i = 0; i < array.length; i++){
            System.out.println("Enter value: ");
            array[i] = sc.nextInt();
        }
        int temp;
        for(int i = 0; i < array.length; i++) {
            for(int j = 0; j < array.length - 1; j++) {
                if(array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = array[j];
                }
            }
        }
        System.out.print("Sorted Array: ");
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

当我输入数组时。输出是:

Enter value: 
5
Enter value: 
4
Enter value: 
3
Enter value: 
2
Enter value: 
1
Sorted Array: 1 1 1 1 1 

4 个答案:

答案 0 :(得分:1)

您的整数交换逻辑不正确。

替换此行

array[j + 1] = array[j];

array[j + 1] = temp;

答案 1 :(得分:0)

您需要更改此行

array[j + 1] = array[j];

到这个

array[j + 1] = temp;

答案 2 :(得分:0)

import java.util.Scanner;
public class BubbleSort{
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        int[] array = new int[5];
        for(int i = 0; i < array.length; i++){
            System.out.println("Enter value: ");
            array[i] = sc.nextInt();
        }
        int temp;
        for(int i = 0; i < array.length; i++) {
            for(int j = 0; j < array.length - 1; j++) {
                if(array[j] > array[j + 1]) {
                    temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp; // ###### here is the change ######
                }
            }
        }
        System.out.print("Sorted Array: ");
        for(int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }
    }
}

改进

在每一步中,最大的元素都在最右边的位置移动。因此,您不需要每次都将内循环迭代到最右侧。

for(int i = 0; i < array.length; i++) {
    for(int j = 0; j < array.length - i - 1; j++) { // early pruning of loop
        if(array[j] > array[j + 1]) {
            temp = array[j];
            array[j] = array[j + 1];
            array[j + 1] = temp;
        }
    }
}

答案 3 :(得分:0)

你忘记分配温度:

array[j + 1] = array[j];

应该是

array[j + 1] = temp;

此外,由于数组的右侧已经排序,您可以在内循环执行中跳过该部分以获得性能提升。

如果您想查看完整参考资料,这是我的完整代码。

public int[] bubbleSort(int[] list) {
  int len = list.length;
  if (len <= 1) 
    return list;

  for (int i = 0; i < len - 1; i++) {
     // The right side of the list is ordered and have no need to check
    for (int j = 0; j < len - i - 1; j++) { 
      if (list[j] > list[j + 1]) {
        int temp = list[j];
        list[j] = list[j + 1];
        list[j + 1] = temp;
      }
    }
  }     
}