0

TXT ファイルをソートする 2 番目のオプションとしてバブル ソートを実装したいと考えています。どんな解決策も高く評価されます。これが私がこれまでに行ったことです。選択ソートを適切かつ正しく初期化できましたが、バブルソートを初期化して同じように動作させることはできません。

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
}
}

}
4

0 に答える 0