JAVA IO Sort Read data from file Sort the data Output data i

JAVA

I/O Sort Read data from file Sort the data Output data into a new file 2D Array (checkers board example)

Solution

Hi, Please find my implementation.

Please let me know in case of any issue.

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileWriter;

import java.io.IOException;

import java.util.Scanner;

public class Sort {

  

   public static void selectionSort(int arr[], int n)

{

// One by one move boundary of unsorted subarray

for (int i = 0; i < n-1; i++)

{

// Find the minimum element in unsorted array

int min_idx = i;

for (int j = i+1; j < n; j++)

if (arr[j] < arr[min_idx])

min_idx = j;

// Swap the found minimum element with the first

// element

int temp = arr[min_idx];

arr[min_idx] = arr[i];

arr[i] = temp;

}

}

  

   public static void main(String[] args) throws IOException {

      

       Scanner input = new Scanner(System.in);

       System.out.print(\"Enter input file name: \");

       String inputFile = input.next();

       System.out.print(\"Enter output file name: \");

       String outputFile = input.next();

      

       // opening input file

       Scanner scanner = new Scanner(new File(inputFile));

       // creating an array of size 100

       int [] numbers = new int [100];

       int i = 0;

      

       // reading numbers and storing in array

       while(scanner.hasNextInt())

       {

           numbers[i++] = scanner.nextInt();

       }

      

       input.close();

       scanner.close();

      

       // calling sort function

       selectionSort(numbers, i);

      

       // writing in file

       FileWriter fw = new FileWriter(outputFile);

       BufferedWriter bw = new BufferedWriter(fw);

      

       for(int j=0; j<i; j++){

           bw.write(Integer.toString(numbers[j])+\" \");

       }

      

       // closing file

       bw.close();

       fw.close();

      

       System.out.println(\"Successfully written to file!!!\");

      

   }

}

/*

Sample run:

Enter input file name: input.txt

Enter output file name: output.txt

Successfully written to file!!!

############ input.txt ##########

12 34 56

1 9 4 6 2

76 54 23 12

########## Output.txt ############

1 2 4 6 9 12 12 23 34 54 56 76

*/

JAVA I/O Sort Read data from file Sort the data Output data into a new file 2D Array (checkers board example)SolutionHi, Please find my implementation. Please l
JAVA I/O Sort Read data from file Sort the data Output data into a new file 2D Array (checkers board example)SolutionHi, Please find my implementation. Please l
JAVA I/O Sort Read data from file Sort the data Output data into a new file 2D Array (checkers board example)SolutionHi, Please find my implementation. Please l

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site