我想实现冒泡排序作为排序TXT文件的第二个选项。任何解决方案将受到高度赞赏。这是我到目前为止所做的。我已经能够正确且正确地初始化选择排序,但无法初始化冒泡排序以使其工作相同。
import java.util.Scanner;
import java.io.*;
public class ArraySort1 {
public static void main(String[] args) throws IOException {
Scanner inputFile;
inputFile = new Scanner(new File("arrayex1.txt"));
PrintWriter outputFile;
outputFile = new PrintWriter(new FileWriter("sorted.txt"));
/* Declare the array */
int[] numbers = new int[50];
int index = 0;
int temp, smallest, smallest_index;
/* Read the first number */
numbers[index] = inputFile.nextInt();
while(inputFile.hasNextInt()) {
numbers[index] = inputFile.nextInt();
index++;
}
// Local variable
int swValue;
// Display menu graphics
System.out.println("============================");
System.out.println("| MENU SELECTION DEMO |");
System.out.println("============================");
System.out.println("| Options: |");
System.out.println("| 1. Selection Sort |");
System.out.println("| 2. Bubble Sort |");
System.out.println("| 3. Exit |");
System.out.println("============================");
swValue = Keyin.inInt(" Select option: ");
// Switch construct
switch (swValue) {
case 1:
System.out.println(" Selection Sort Starting....");
for (int i = 0; i < index - 1; i++) {
smallest = numbers[i];
smallest_index = i;
for (int j = i + 1; j < index; j++) {
if (numbers[j] < smallest) {
smallest = numbers[j];
smallest_index = j;
}
}
/* If needed switch numbers[i] and numbers[smallest_index] */
if (numbers[i] != numbers[smallest_index]) {
temp = numbers[i];
numbers[i] = numbers[smallest_index];
numbers[smallest_index] = temp;
}
}
for (int i = 0; i < index; i++) {
System.out.print (numbers[i] + " ");
outputFile.print (numbers[i] + " ");
}
inputFile.close();
outputFile.close();
break;
case 2:
int i = 0, t=0;
boolean swapped = true;
while(swapped){
swapped = false;
for(int i1 = 0; i1 < index - 1; i1++){
smallest = numbers[i1];
smallest_index = i1;
if(numbers[i1] > numbers[i1 + 1]){
swapped = true;
int tmp = numbers[i1];
numbers[i1] = numbers[i1 + 1];
numbers[i1 + 1] = tmp;
}
}
for(int i1 = 0; i < numbers.length; i++){
System.out.print(numbers[i] + "\t");
}
System.out.println();
}
//2 System.out.println("Bubble Sort Sorting 2 selected");
break;
case 3:
System.out.println("Exit selected");
break;
default:
System.out.println("Invalid selection");
break; // This break is not really necessary
}
}
}