【问题标题】:Trying to Bubble Sort in java尝试在java中进行冒泡排序
【发布时间】:2017-04-25 15:46:18
【问题描述】:

尝试编写代码,以便通过冒泡排序对用户输入的数字列表进行排序。这是我到目前为止所拥有的:

import java.util.Scanner;

public class BubbleSort
{    
    public static void main(String[] args)
    {
        int n; 

        int[] list[];
        System.out.println("Please enter number of the elements to be sorted");
        Scanner keyboard = new Scanner(System.in);
        n = keyboard.nextInt();

        for ( int pass = 1; pass < n; pass++)
            for (int i = 0; i < n - pass ; i++)
                {
                    if (list[i] > list[i + 1]){
                        int temp = list[n];
                        list[i] = list[i + 1];
                        list[i + 1] = temp;
                    }
                }

    }

}

我收到以下错误提示

The operator > is undefined for the argument type(s) int[], int[]" for the line: if (list[i] > list[i + 1])

type mismatch: cannot convert from int[] to int" for line: int temp = list[n];

Type mismatch: cannot convert from int to int[]" for line: list[i + 1] = temp;

非常感谢您的宝贵时间和帮助。

【问题讨论】:

  • 您的气泡交换中至少存在一个错误。 int temp = list[n]; 应该是 int temp = list[i];

标签: java arrays sorting bubble-sort


【解决方案1】:
package com.borntoinnovation.datastructure;

import java.util.Arrays;

//Sort between value like 0-1, 1-2, 2-3, 3-4, 4-5 :Suppose end is 5
//0-1, 1-2, 2-3, 3-4 ( 5th already sorted into their position
//0-1, 1-2, 2-3 (4th sorted)
//.... like that
public class SortingBubble {

    public static void main(String[] args) {
        int[] array = new int[] { 40, 10, -30, 45, 39, 32 };

        for (int i = 0; i < array.length - 1; i++) {
            for (int j = 0; j < array.length - 1 - i; j++) {
                if (array[j] < array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
            System.out.println(Arrays.toString(array));
        }
    }
}

/*
 * [40, 10, 45, 39, 32, -30] 
 * [40, 45, 39, 32, 10, -30] 
 * [45, 40, 39, 32, 10, -30]
 */

【讨论】:

  • 虽然此代码可能会解决问题,including an explanation 关于如何以及为什么解决问题将真正有助于提高您的帖子质量,并可能导致更多的赞成票。请记住,您正在为将来的读者回答问题,而不仅仅是现在提问的人。请编辑您的答案以添加解释,并说明适用的限制和假设。
【解决方案2】:

您刚刚使用此int[] list[]; 声明了一个2D 数组。二维数组是数组的数组,可以这样声明

int list[][];
int []list[];
int[] list[];

但您的要求是一维数组,应该这样声明

 int[] list;
 int list[];

另外你忘记了你的数组的初始化并从用户那里获取数组数据值,来初始化数组

 n = keyboard.nextInt();
 list=new int[n]; // initialize array length  

要从 user 获取数组值,您需要再次循环 n 次并使用 keyboard.nextInt(); 获取输入以获取所有数组值

请参阅this example 以正确实现您的逻辑

【讨论】:

  • 非常感谢您的澄清和帮助很大的示例
猜你喜欢
  • 2011-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-14
  • 2014-06-25
  • 2017-06-17
  • 2016-06-09
  • 2021-06-29
相关资源
最近更新 更多