尝试在java中冒泡排序

时间:2016-12-10 06:06:37

标签: java arrays sorting bubble-sort

尝试编码,以便用户输入的数字列表通过气泡排序进行排序。这就是我到目前为止所做的:

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;

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

2 个答案:

答案 0 :(得分:1)

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

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

但你的要求是1D数组,应该像这样声明

 int[] list;
 int list[];

此外,您忘记了数组的初始化并从用户获取数组数据值,以初始化数组

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

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

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

答案 1 :(得分:-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]
 */