Second: Arrays and Sorting (10 points) In the second part, you have to write a p
ID: 3586731 • Letter: S
Question
Second: Arrays and Sorting (10 points)
In the second part, you have to write a program that will read an array from a file and sort the given array. You will return the array sorted in ascending order. You can use any sorting algorithm you know or wish to use. However, you cannot use the library sort functions. You should write your own sort function.
Input-Output format: Your program will take the file name as input. The first line in the file provides total number of values in the array. The second line will contain a list of numbers separated by tabs:
For example, a sample input file “file1.txt” is:
5
12 54 10 4 8
Your output will be the sorted list of numbers, each separated by tab.
$./second file1.txt
4 8 10 12 54
We will not give you improperly formatted files. You can assume all your input files will be in proper format as above.
Explanation / Answer
/**
* I've uploaded the source code to https://gist.github.com/anonymous/80dd45aac914bf1647f6b44edbab8bda
* "file.txt" must be present in the same directory as the program
*/
import java.io.*;
import java.util.*;
class FileArraySort {
/**
* Sorts and returns an array using bubble sort.
* arr - array to be sorted
*/
private static int[] bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (arr[j - 1] > arr[j]) {
//swap elements
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
return arr;
}
public static void main(String[] args) {
String line = null;
try {
BufferedReader br = new BufferedReader(new FileReader("file1.txt"));
line = br.readLine();
br.close();
} catch (IOException e) {
System.out.println("Error occured in reading file");
System.exit(1);
}
// Adding numbers into array list
String []strNumbers = line.split(" ");
int [] arr = new int[strNumbers.length];
int index = 0;
for(String strNumber : strNumbers){
arr[index++] = Integer.parseInt(strNumber);
}
// Sorting the numbers
arr = bubbleSort(arr);
// Printing sorted array
for (index=0; index < arr.length; index++) {
System.out.print(arr[index] + " ");
}
System.out.println();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.