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. JAVA CODE
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];
int n = 0;
while(in.hasNext())
{
a[n] =
in.nextInt();
n++;
}
bubbleSort(a, n);
System.out.println("Sorted List: ");
for(int i=0; i<n; i++)
{
System.out.println(a[i]);
}
}
}
num.txt
15 36 62 16 43
29 43 9 33 5
44 78 21 8 29
Output:
java BubbleSort num.txt
Sorted List:
5
8
9
15
16
21
29
29
33
36
43
43
44
62
78
N.B. Whether you face problem then share with me in the comment
section, I'll help you. I expect positive feedback from your
end.