[英]Bubble Sort numbers from file in java
我正在尝试对文本文件中的数字进行冒泡排序,我了解如何对文本进行冒泡排序以及如何使用文本文件。 但是从来没有同时使用过它们。 我尝试对数组进行冒泡排序,只是试图弄清楚如何用文本文件替换该数组。 如果有人可以向我解释如何使气泡排序以读取文本文件,将不胜感激。 我是Java的新手,有时将我学到的2种不同的东西组合到1个程序中会感到困惑。
这是我解决数组的冒泡排序:
public static void main(String[] args)
{
int number[]={7,13,4,5,62,3,1,3,45};
int temp;
boolean fixed=false;
while(fixed==false){
fixed = true;
for (int i=0; i <number.length-1;i++){
if (number[i]>number[i+1]){
temp = number [i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for (int i=0; i<number.length;i++){
System.out.println(number[i]);
}
}
}
使用Scanner类!
File file=new File("file.txt");
Scanner sc=new Scanner(file);
int arr[]=new int[100];
int i=0;
while(sc.hasNextLine()){
arr[i]=sc.nextInt();
i++;
}
不要只是对数组进行硬编码..!
假设文件的内容是一个数字列表,该数字列表之间用一些定界符隔开,例如“
采用:
File file=new File("file.txt");
Scanner sc=new Scanner(file);
String arr[] = sc.nextLine().split(" ");
这就对了。 一旦获得阵列,您就可以使用它。
您可以这样:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [256];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}
读取文件与冒泡排序无关。 您可以读取文件以创建整数数组,然后使用常规的冒泡排序算法对其进行排序
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.