[英]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.