gpt4 book ai didi

java - 实现 bubbleSort 后未获得正确的输出

转载 作者:行者123 更新时间:2023-12-01 14:21:26 26 4
gpt4 key购买 nike

该程序创建一个名为 datafile.txt 的文件,并使用文本 I/O 将随机创建的 100 个整数写入该文件。我还实现了 bubbleSort 以升序对数字进行排序,但它没有对它们进行排序。另外,命令行的输出是“排序后的数字是:[I@f72617”100 次。提前致谢。

   import java.io.*;
import java.util.Random;

public class Lab5 {

//sort array
static int[] bubbleSort(int[] array) {

for (int pass = 1; pass <= 100; pass++) {
for (int current = 0; current < 100-pass; current++) {

//compare element with next element
if (array[current] > array[current + 1]) {

//swap array[current] > & array[current + 1]
int temp = array[current];
array[current] = array[current + 1];
array[current + 1] = temp;
} //end if
}
}
return array;
}
public static void main(String args[]) {

//Open file to write to
try {
FileOutputStream fout = new FileOutputStream("F:\\IT311\\datafile.txt");


int index = 0;

//Convert FileOutputStream into PrintStream
PrintStream myOutput = new PrintStream(fout);
Random numbers = new Random();
//Declare array
int array[] = new int[100];
for (int i = 0; i < array.length; i++)
{
//get the int from Random Class
array[i] = (numbers.nextInt(100) + 1);

myOutput.print(array[i] + " ");

//sort numbers
int[] sortedArray = bubbleSort(array);

//print sorted numbers
System.out.print("The sorted numbers are: ");
System.out.print(sortedArray);
}
}
catch (IOException e) {
System.out.println("Error opening file: " + e);
System.exit(1);
}
}

}

最佳答案

使用如下:

System.out.print(Arrays.toString(sortedArray));

关于java - 实现 bubbleSort 后未获得正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519380/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com