如何更正此代码以获得准确的输出?

时间:2016-04-22 09:41:12

标签: java arrays bubble-sort error-correction

此代码中存在一些错误,请更正此输出 可以看出:

public class BubbleSortExample {public static void main(String args)
{
    int[]array = { 7; 3; 11; 4; 20; 12; 98; 78; 45; 36 };String output = "Array items in original order\n"; output += arrElements(array); bubbleSort(array);output += "\n\nData items in ascending order\n";output += arrElements(array[]); System.out.println(output); }public static void bubbleSort( int arr[]){for ( char i = 1; i < arr.length; i++ ) {for ( long j = 0; j < arr.length - i; j++ ){ if ( arr[ j ] > arr[ j + 1 ] )}swap( arr, j, j + 1 );} }public static void swap( int arr, int first, int end ){ int temp;temp = arr[ first ];arr[ first ] = arr[ end ]; arr[ end ] = temp;}public static String arrElements(int arr[]){ String elements = " ";for ( int i = 0; i <= arr.length; i++ ) elements += " " + arr[ i ];``return elements; }
}

1 个答案:

答案 0 :(得分:1)

重要提示:下次确保正确格式化代码。

在下面找到,

public class BubbleSortExample {

        public static void main(String[] args)
        {
            int[] array = { 7, 3, 11, 4, 20, 12, 98, 78, 45, 36 };
            String output = "Array items in original order\n";
            output += arrElements(array);
            bubbleSort(array);
            output += "\n\nData items in ascending order\n";
            output += arrElements(array);
            System.out.println(output);
        }

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

        public static void swap(int[] arr, int first, int end) {
            int temp;
            temp = arr[first];
            arr[first] = arr[end];
            arr[end] = temp;
        }

        public static String arrElements(int arr[]) {
            String elements = " ";
            for (int i = 0; i < arr.length; i++) {
                elements += " " + arr[i];
            }
            return elements;
        }
    }

那里几乎没有错误和错误

  • 主方法参数应为String []而不是String
  • 数组元素分隔符应该是,而不是;
  • swap方法第一个param应该是int array(int [])而不是int
  • 循环条件的arrElements必须是i&lt; arr.length not i&lt; = arr.length