Bubble Sort numbers from file in java - java

I am trying to bubble sort numbers from a text file, I understand how to bubble sort and how to use a text file. But have never used both of them at the same time. I tried bubble sorting an array and just trying to figure out how to replace that array with a text file. If someone can explain to me how to get the bubble sort to read a text file it would be greatly appreciated. I am new to java and it is sometimes confusing to combine 2 different things I have learned into 1 program.
Here is my bubble sort that solves the array:
public static void main(String[] args)
{
int number[]={7,13,4,5,62,3,1,3,45};
int temp;
boolean fixed=false;
while(fixed==false){
fixed = true;
for (int i=0; i <number.length-1;i++){
if (number[i]>number[i+1]){
temp = number [i+1];
number[i+1]=number[i];
number[i]=temp;
fixed=false;
}
}
}
for (int i=0; i<number.length;i++){
System.out.println(number[i]);
}
}
}

Use Scanner class !
File file=new File("file.txt");
Scanner sc=new Scanner(file);
int arr[]=new int[100];
int i=0;
while(sc.hasNextLine()){
arr[i]=sc.nextInt();
i++;
}

Don't just hard code the array..!
Suppose the content of your file is a list of number separated by some delimiter say single space " "
Use:
File file=new File("file.txt");
Scanner sc=new Scanner(file);
String arr[] = sc.nextLine().split(" ");
That is it.
Once you have got the array u can play around with it..!

Reading a file has nothing to do with bubble sort. You can read the file to create an array of integers and then use the usual bubble sort algorithm to sort it

You can do like this:
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
import java.util.Scanner;
public class Test {
public static void bubbleSort(int[] num ) {
int j;
boolean flag = true; // set flag to true to begin first pass
int temp; //holding variable
while ( flag ) {
flag= false; //set flag to false awaiting a possible swap
for( j=0; j < num.length -1; j++ ) {
if ( num[ j ] < num[j+1] ) {
temp = num[ j ]; //swap elements
num[ j ] = num[ j+1 ];
num[ j+1 ] = temp;
flag = true; //shows a swap occurred
}
}
}
}
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(new File("numbers.txt"));
int [] numbers = new int [256];
int i = 0;
while(scanner.hasNextInt()){
numbers[i++] = scanner.nextInt();
}
bubbleSort(numbers);
System.out.println(Arrays.toString(numbers));
}
}

Related

Need help in finding where to start looking to fix my code. When reading large files it gets stuck

I'm trying to read a large text file of about 7516 lines of text. When I read a smaller file (9 lines) the program works fine. But with the large file it seems to get caught in something and just keeps running without anything actually happening.I'm not sure where to start looking for the issue.
The code reads a text file and then turn it into an array. Then it passes the array into a shuffle and writes it into another text file. Or at least that's what I want it to do.
package Rn1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Random;
import java.util.Scanner;
public class Read2 {
static void randomShuffle( int arr[], int n)
{
// Creating a object for Random class
Random r = new Random();
// Start from the last element and swap one by one. We don't
// need to run for the first element that's why i > 0
for (int i = n-1; i > 0; i--) {
// Pick a random index from 0 to i
int j = r.nextInt(i+1);
// Swap arr[i] with the element at random index
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
// Prints the random array
System.out.println(Arrays.toString(arr));
}
public static String readString(String file) {
String text = "";
try {
Scanner s = new Scanner(new File(file));
while(s.hasNext()) {
text = text + s.next() + " ";
}
}
catch(FileNotFoundException e) {
System.out.println("Not Found");
}
return text;
}
public static String[] readArray(String file) {
//Step 1:
//Count how many elements in the file (lines)
//Step 2
//Create array
int ctr = 0;
try {
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()) {
ctr = ctr +1;
if (s1.hasNext()) {
s1.next();
}
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for(int i = 0; i < ctr; i = i+1){
words[i] = s2.next();
}
return words;
}
catch (FileNotFoundException e) {
}
return null;
}
public static void main(String[] args) throws Exception
{
//String text = readString("C:\\Users\\herna\\Desktop\\Test.txt");
//System.out.println(text);
String[] words = readArray("C:\\Users\\herna\\Desktop\\ErdosCA.txt");
int n = words.length;
int [] arr = new int [n];
PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
for (int i=0; i < words.length; i = i + 1 )
{
arr[i] = Integer.parseInt(words[i]);
//writer.println(words[i]);
}
//System.out.println(Arrays.toString(arr));
randomShuffle(arr, n);
writer.println(Arrays.toString(arr));
//writer.println(Arrays.toString(words));
//writer.println("Update*");
writer.close();
}
}
The program is also reproducable with small files, for example:
1
2
3
The program enters an endless loop when the last line of the file is empty. The bad part is this:
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine())
{
ctr = ctr + 1;
if (s1.hasNext())
{
s1.next();
}
}
If you are before the empty line, then s1.hasNextLine() is true but s1.hasNext() is false. So you do not read the next element. Then in the next iteration of the loop, s1.hasNextLine() is still true, and thus the loop does never end.
By the way, you should never catch Exceptions without handling them. You should at least output an error message and then call e.printStackTrace().

reading .txt file and making an array(java)

Im trying to read in a .txt file and make a multi dimensional array out of it. I dont understand why the i and j loops arent populating my array. Any pointers much appreciated....
import java.util.*;
import java.io.*;
public class arrayChallenge {
public static void main(String[] args) throws FileNotFoundException{
File input = new File("input.txt");
Scanner scan1 = new Scanner(input);
int width=10, height=10;
char [][] arrayMulti = new char[width][height];
for(int i=0; i<height; i++){
String x = scan1.next();
char[] chars = x.toCharArray();
for(int j=0; j<width; j++){
arrayMulti[i][j]= chars[j];
}
}
for(char [] xy: arrayMulti){
System.out.println(Arrays.toString(xy));
}
}
}
There is nothing wrong with your i and j loops as far as I can see. As long as the provided path to your file is correct and the file has the needed number of lines (>= your width variable) and each line has the needed number of characters (>= your height variable), it should work fine.

I'm trying to sort an Array List of strings in ABC order without using a pre-made class

Im having trouble sorting my array list in ABC order. This is what I have so far, any ideas on how to achieve it? My output is switching some of the words, but not putting the whole array list in ABC order. I'm lost, as you can tell from my loops at the end =[
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListLab
{
public static void main (String [] args)
{
Scanner scan = new Scanner (System.in);
ArrayList <String> words = new ArrayList <String> ();
for (int x = 0; x < 10; x++)
{
System.out.println("Pick a word, any word!");
words.add(scan.nextLine());
}
for (int x = 0; x < 9; x++)
{
words.get(x).compareTo(words.get(x+1));
if (words.get(x).compareTo(words.get(x+1))>0)
{
String temp = words.get(x+1);
words.set((x+1),words.get(x));
words.set(x, temp);
}
else
if (words.get(x).compareTo(words.get(x+1))<0)
{
words.get(x);
}
else
if(words.get(x).compareTo(words.get(x+1))==0)
{
words.get(x);
}
}
System.out.println(words);
}
}

Read and Sort a file to array Java

I'm attempting to write a program that would read a file "data.txt" which has an undefined amount of numbers in random order, separated by line. It would add these numbers into an array and print out the numbers in one line, each separated by a comma "x, x1". Then on the next line it would print out (in the same format) the list of numbers which has been sorted from smallest to largest size.
Data type is integer.
Currently, I have coded for 3 methods which would allow the array to be sorted (I think they have no error).
I've created another method to read the file and am using a two-step process - once to figure out the number of lines in the file (I ask that this two-step process remain). This method seems to have trouble returning the "lineCount" and apparently I need to make this variable an array (which I find bizarre). How can I fix this code?
You may notice that my method for printing is empty; I have not figured out a way to print the array so that each number is separated by a comma. How do I code for this?
My code so far:
import java.util.*;
import java.io.*;
public class SortAndSearch {
public static void main(String[] args) {
readFile2Array();
printArray();
selectionSort();
printArray();
}
public static void printArray(int[] a) {
}
public static void selectionSort(int[] a) {
int minI = 0;
for (int k = 0; k < a.length - 1; ++k) {
minI = findMinIdx(a, k); // findMinIdx at k-th
swapElement(a, k, minI);// swapElement at k-th
}
}
public static int findMinIdx(int[] a, int k) {
int minIdx = k;
for (int i = k + 1; i < a.length; ++i)
if (a[i] < a[minIdx])
minIdx = i;
return minIdx;
}
public static void swapElement(int[] a, int i, int j) {
int temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
public static int[] readFile2Array(String fileName) {
File dat = new File("data.txt");
int lineCount = 0;
int[] a = new int[lineCount];
int i;
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
}
catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
}
public static int binarySearch(int[] arr, int val){
int minIdx, maxIdx, index = -1;
while(){ int middleIdx = (minIdx + maxIdx)/2;
if( arr[???] ==val){
index = middleIdx;
break } // update minIdx, maxIdx //if smaller then cut right, if larger then cut left
}
return index; }
}
The last method in the program would attempt to locate the element number of a user inputted number by using this (pseudo)code:
1. Let ‭min = 0‬ and ‭max = n-1‬ (where n is the array’s length)‬‬‬‬
2. If ‭max < min‬, then stop: ‭target‬ is not present in ‭array‬. return ‭false‬.‬‬‬‬‬‬‬‬
3. Compute ‭guess‬ as the average of ‭max‬ and ‭min‬, rounded down (so that it is an integer).‬‬‬‬‬‬
4. If ‭array[guess]‬ equals ‭target‬, then stop. You found it! Return ‭guess‬.‬‬‬‬‬‬
5. If the guess was too low, that is, ‭array[guess] < target‬, then set ‭min = guess + 1‬.‬‬‬‬
6. Otherwise, the guess was too high. Set ‭max = guess - 1‬.‬‬
7. Go back to step 2.
How would I code for this?
I would really appreciate any help in any area of this program!
Managed to fix the first part of the code:
readFile2Array method:
public static int[] readFile2Array(String fileName) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) { // first read to count -> int lineCount;
lineCount++; // second read to array -> hasNext(),
sc.nextLine();
}
sc.close();
sc = new Scanner(new File("data.txt"));
int[] x = new int[lineCount];
int n = 0;
while (sc.hasNext()) {
x[n] = Integer.parseInt(sc.nextLine());
n++;
}
sc.close();
return x;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
}
return null;
}
Print array separated by comma:
public static void printArray(int[] a) {
try {
int lineCount = 0;
Scanner sc = new Scanner(new File("data.txt"));
while (sc.hasNext()) {
lineCount++;
sc.nextLine();
}
sc.close();
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < lineCount-1) System.out.print(", ");
}
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
}
System.out.println();
}
Last method is still a mystery to me though!
I agree with VGR that you haven't actually asked a question, but by reading your code I guess that you were describing what you wanted to achieve...
There are some flaws in your readFile2Array-method, which might solve the problem:
1)
int lineCount = 0;
int[] a = new int[lineCount]; //The size of a will always be 0, so you can't add anything to it, even though you are trying to do this later. Consider using a List instead, as the size of the list can increase dynamically.
2)
while (sc.hasNextLine()){ //first read to count -> int lineCount;
lineCount++;
return lineCount; //I have trouble with this line
}
//The problem is the return type: You method signature states that you will return int[], but here you are trying to return an int.
//It will also just increase lineCount once and try to return this.
3)
//Your scanning will be at the 2nd line because of 2) and not going through the entire file again. To do this you need to create a new instance of Scanner. And the int[] a has a size of 0 at this point.
while (sc.hasNextLine()){ //second read to array -> hasNext(),
a[i] = sc.nextInt();
return a;
}
So in order to solve this you should refactor your code to something like:
public static List<Integer> readFile2Array(String fileName) {
File dat = new File("data.txt");
List<Integer> a = new ArrayList<>();
try{ Scanner sc = new Scanner(dat);
while (sc.hasNextLine()){
a.add(sc.nextInt());
}
sc.close(); //Always remember to close, when done :)
System.out.println("Added " + a.size() + " lines to the list.");
return a;
} catch (FileNotFoundException e) {
System.out.println("File cannot be opened");
e.printStackTrace();
return new ArrayList<>();
}
}
What I changed:
removed the lineCount as this is implicit stored in the size of the list called a.
Changed the int[] a to a List as this always will allow adding elements by increasing its size when needed.
Removed i as was never used, only initialized.
Removed the first while-loop as we don't need to know the amount of lines that is going to be added.
Added a return-statement in the catch-closure. We need to return something (even an empty array or maybe the not-yet-finished array)
I hope this helps. :)
I'm glad you got that part working. :)
To print out the array, it will be best to use whatever data you have of the array. By calling a.length, you don't have to count the number of lines from the input again, which you are not guaranteed are still the same if the input has changed in the mean time.
So this piece of code should do the trick:
public static void printArray(int[] a) {
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i]);
if (i < a.length-1) System.out.print(", ");
}
System.out.println();
}

prime1 spoj generating prime numbers between two number

package primesieve1;
import java.io.InputStreamReader;
import java.util.Scanner;
public class Primesieve1 {
public boolean[] sieveOfEratosthenes(int max){
boolean[] primeno; //defaults to false
primeno = new boolean[max];
for(int i=2; i<max; i++ ){primeno[i]=true;}
for(int i=2; i<Math.sqrt(max);i++){
if(primeno[i] == true){
//all multiples of i*i, except i, are not primeno
for(int j = i + i; j<max; j=j+i){
primeno[j]=false;
}
}
}
return primeno;
}
public void printTrue(boolean[] arr){
for(int i=0; i<arr.length; i++){
if(arr[i]==true){
System.out.print(i + ", ");
}
}
}
public static void main(String[] args) {
System.out.println("enter limit");
Scanner sc = new Scanner(new InputStreamReader(System.in));
int a = sc.nextInt();
boolean a1[];
Primesieve1 obj = new Primesieve1();
a1 = obj.sieveOfEratosthenes(a);
obj.printTrue(a1);
}
}
giving out this error didnt understand why
java.lang.OutOfMemoryError: Java heap space
Although I'm not 100% sure I think a boolean[] still uses about 1 byte per entry. Max will probably get quite big so even increasing the memory for the JVM will probably not do the trick.
One thing you can do however is not use a boolean[] but a BitSet instead, this way you'll only use 1 bit per number and thus you can probably cover until the max value of int.

Categories