I posted this multiple times, but no one was able to solve myproblem. So I made
ID: 3617489 • Letter: I
Question
I posted this multiple times, but no one was able to solve myproblem. So I made a video of the problem I am having. Here is thelink to the vid.http://www.youtube.com/watch?v=DlMXeTvvUd8
My Code 1:
class read{ //established name
public static void main(String[] args) { //main args
readfile r = new readfile(); //establishsthat we will be reading a file
r.openFile(); //opens the file
r.readFile(); //reads it
r.closeFile(); //safely closes it
r.mergesort();
r.merge();
}
}
My Code 2:
import java.io.*;
import java.util.*;
import javax.swing.*;
public class readfile
{
private Scanner x;
String m = JOptionPane.showInputDialog("enter name of file:");
public void openFile()
{
try
{
x = new Scanner(new File(m));
}
catch(FileNotFoundException e)
{
JOptionPane.showMessageDialog(null, "Error 504: File Notfound");
}
}
int a;
int tot;
ArrayList<Integer> arr = newArrayList<Integer>();
public void readFile()
{
int place;
while(x.hasNext())
{
place = 0;
a = x.nextInt();
arr.add(a);
}
JOptionPane.showMessageDialog(null,"This is thearray before the sort " + arr);
tot = arr.size();
JOptionPane.showMessageDialog(null, tot);
}
public void mergesort()
{
mergesort(arr, 0, arr.size());
}
private static void mergesort(ArrayList<Integer> list,int start, int end)
{
// a list of size 0 or 1 is merged
if(end-start<2)
{
return;
}
// divide into 2 pieces
int mid = (start+end)/2;
mergesort(list, start, mid);
mergesort(list, mid, end);
// merge together
merge(list, start, mid, end);
}
public void merge()
{merge(arr,0,arr.size()/2,arr.size());
}
private static void merge(ArrayList<Integer> list, intstart, int mid, int end)
{
// temp storage
Integer[] temp = new Integer[end-start];
int loc = 0;
int i = start;
int j = mid;
// add elements to temp
while(i < mid && j < end)
{
if(list.get(j).compareTo(list.get(i)) < 0)
{
// add element from 2ndlist
temp[loc++] =list.get(j++);
}
else
{
temp[loc++] =list.get(i++);
}
}
// add remaining elements to list
while(i < mid)
{
temp[loc++] = list.get(i++);
}
while(j < mid)
{
temp[loc++] = list.get(j++);
}
// put elements back into list from temp
for(int t = 0; t < temp.length; t++)
{
list.set(t + start, temp[t]);
}
}
public void closeFile()
{
x.close();
}
}