In: Computer Science
Create a program called BubleSort.java that implements the Bubble Sort algorithm (The Art of Computer Programming - Donald Knuth). The algorithm is as follows: The program should be able to do the following: accepts one command line parameter. The parameter specifies the path to a text file containing the integers to be sorted. The structure of the file is as follows: There will be multiple lines in the file (number of lines unknown). Each line will contain multiple integers, separated by a single whitespace. reads the integers from the text file in part a into an array of integers. sort the integers in ascending order, and then prints out a sorted version of these integers, one per line. The implementation should follow the given the pseudo code/algorithm description.
Program
import java.util.*;
import java.io.*;
//class BubbleSort
public class BubbleSort
{
//method to perform bubble Sort
public static void bubbleSort(int arr[], int n)
{
while(true)
{
int t = 0;
for(int j=0; j<n-1;
j++)
{
if(arr[j]>arr[j+1])
{
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
t = j+1;
}
}
if(t==0) break;
}
}
//main method
public static void main(String args[]) throws IOException
{
File file = new File(args[0]);
//create object of Scanner class
Scanner in = new
Scanner(file);
//declare the array
int a[] = new int[1000];
//read data from file
int n = 0;
while(in.hasNext())
{
a[n] =
in.nextInt();
n++;
}
bubbleSort(a, n);
//print the sorted list
System.out.println("Sorted List: ");
for(int i=0; i<n; i++)
{
System.out.println(a[i]);
}
}
}
input.txt
25 37 52 26 34
92 43 99 37 59
40 79 22 81 25
29 37 52 28 35
Output:
java BubbleSort input.txt
Sorted List:
22
25
25
26
28
29
34
35
37
37
37
40
43
52
52
59
79
81
92
99