I'm trying to implement a Deque utilizing a circular array that extends when the array gets full. However, I am getting an IndexOutOfBoundsException. I think my issue is with the insertLast method. I've analyzed my code thoroughly and I cannot see what I am doing wrong. Any assistance would be greatly appreciated.
public class CircularExtendedArrayDeque
{
public static final int INIT_CAPACITY = 4; // initial array capacity
protected int capacity; // current capacity of the array
protected int front; // index of the front element
protected int rear; // index of the rear element
protected int[] A; // array deque
public CircularExtendedArrayDeque( ) // constructor method
{
A = new int[ INIT_CAPACITY ];
capacity = INIT_CAPACITY;
front = rear = 0;
}
/**
* Print the content of the deque
*
*/
public void printDeque( )
{
for ( int i = front; i != rear; i = (i+1) % capacity )
System.out.print( A[i] + " " );
System.out.println();
}
/**
* Print the content of the whole array
*
*/
public void printArray( )
{
for ( int i = 0; i < capacity; i++ )
System.out.print( A[i] + " " );
System.out.println();
}
// ***************************************
// DO NOT MODIFY THE CODE ABOVE THIS LINE.
// ADD YOUR CODE BELOW THIS LINE.
//
// ***************************************
/**
* Returns the number of items in this collection.
* #return the number of items in this collection.
*/
public int size()
{
// COMPLETE THIS METHOD
return (capacity - front + rear) % capacity;
}
/**
* Returns true if this collection is empty.
* #return true if this collection is empty.
*/
public boolean isEmpty()
{
// COMPLETE THIS METHOD
return front == rear;
}
/**
* Returns the first element of the deque
*
*/
public int getFirst() throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
return A[front % capacity];
}
/**
* Returns the last element of the deque
*
*/
public int getLast() throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
return A[(front + rear - 1) % capacity];
}
/**
* Inserts e at the beginning (as the first element) of the deque
*
*/
public void insertFirst( int e )
{
// COMPLETE THIS METHOD
rear++;
if(size() == capacity - 1){
capacity *= 2;
}
int[] B = new int[capacity];
for(int i = 0; i < size(); i++){
B[i] = A[i];
}
A = B;
for(int i = size(); i >= front; i--){
A[i+1] = A[i];
}
A[front] = e;
front = front % capacity;
System.out.println("Front: " + front + " & Rear:" + rear);
}
/**
* Inserts e at the end (as the last element) of the deque
*
*/
public void insertLast( int e )
{
// COMPLETE THIS METHOD
if(size() == capacity - 1){
capacity *= 2;
int[] B = new int[capacity];
for ( int i = front; i != rear; i = (i+1) % capacity )
B[i] = A[i];
/*
for(int i = 0; i < size(); i++){
B[i] = A[i];
}
*/
A = B;
A[rear++] = e;
}
else{
//System.out.println("Array Size = " + A.length);
A[rear++] = e;
}
System.out.println("Front: " + front + " & Rear:" + rear);
System.out.println("msg...size=" + size());
}
/**
* Removes and returns the first element of the deque
*
*/
public int removeFirst( ) throws EmptyDequeException
{
// COMPLETE THIS METHOD
int result = A[front];
A[front] = 0;
front = (front+1)%capacity;
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
else if(capacity >= 4){
if(size() < capacity/2){
//System.out.println("msg...size = " + size());
capacity /= 2;
int[] B = new int[capacity];
int counter=0;
for(int i = front; i < front+size(); i++){
B[counter] = A[i%(capacity*2)];
counter++;
}
A = B;
front = 0;
rear = size()-1;
}
}
return result;
}
/**
* Removes and returns the last element of the deque
*
*/
public int removeLast( ) throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
else if(capacity >= 4){
if(size() < capacity/2){
System.out.println("Capacity shrinking...");
int[] B = new int[capacity/2];
for(int i = 0; i < capacity/2; i++){
B[i] = A[i];
}
A = B;
}
}
int temp = A[rear - 1];
A[rear] = 0;
rear = (rear - 1) % capacity;
return temp;
}
} // end class
Here's the main class:
public class CircularExtendedArrayMain {
public static void main(String[] args) {
CircularExtendedArrayDeque q = new CircularExtendedArrayDeque();
q.insertFirst(112);
q.insertFirst(105);
q.printDeque();
System.out.println("last element is = " + q.getLast());
System.out.println("first element is = " + q.getFirst());
q.insertLast(5501);
q.printDeque();
q.insertLast(778);
q.insertLast(37);
q.printDeque();
System.out.println("first element is = " + q.getFirst());
System.out.println("last element is = " + q.getLast());
System.out.println("remove last = " + q.removeLast());
q.printDeque();
System.out.println("remove last = " + q.removeLast());
System.out.println("remove first = " + q.removeFirst());
q.printDeque();
System.out.println("remove first = " + q.removeFirst());
System.out.println("remove first = " + q.removeFirst());
// q is now empty.
int i, k;
for( i = 1; i <= 60; i ++ )
q.insertLast(i*i);
q.printDeque(); // 60 elements in q
for( i = 1; i <= 58; i++ )
k = q.removeFirst();
q.printDeque(); // two elements are left
}
}
Here's my output:
Front: 0 & Rear:1
Front: 0 & Rear:2
105 112
last element is = 112
first element is = 105
Front: 0 & Rear:3
msg...size=3
105 112 5501
Front: 0 & Rear:4
msg...size=4
Front: 0 & Rear:5
msg...size=5
105 112 5501 778 37
first element is = 105
last element is = 37
remove last = 37
105 112 5501 778
remove last = 778
remove first = 105
112 5501
remove first = 112
remove first = 5501
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at CircularExtendedArrayDeque.insertLast(CircularExtendedArrayDeque.java:161)
at CircularExtendedArrayMain.main(CircularExtendedArrayMain.java:34)
public void insertLast(int e) {
if(size() == capacity - 1) {
capacity= capacity*2;
}
int[] B = new int[capacity];
for(int i = 0; i < size(); i++) {
B[i] = A[i];
}
A = B;
A[rear] = e;
rear = (rear + 1) % capacity;
}
This is my insertLast(). Guess this works. Good luck with cse2011.. !!
Related
I am trying to implement min-heap which includes methods like insert,delete and heap sort.I am using implementation of max-heap and trying to convert it to min-heap.But,i am having some minor issues.It's a very straight-forward method ,but i am missing something,which i am not able to get.
This is the Helper Max-heap implementation i am using:
public void trickleDown(int index)
{
int largerChild;
Node top = heapArray[index]; // save root
while(index < currentSize/2) // while node has at
{ // least one child,
int leftChild = 2*index+1;
int rightChild = leftChild+1;
// find larger child
if( rightChild < currentSize && // (rightChild exists?)
heapArray[leftChild].getKey() <
heapArray[rightChild].getKey() )
largerChild = rightChild;
else
largerChild = leftChild;
// top >= largerChild?
if(top.getKey() >= heapArray[largerChild].getKey())
break;
// shift child up
heapArray[index] = heapArray[largerChild];
index = largerChild; // go down
} // end while
heapArray[index] = top; // index <- root
} // end trickleDown()
/////// My Implementation
/** Removes the top element of the heap and returns it.
*
* Complexity: O(log n)
* #return Top (min/max) element of the heap.
* #throws IllegalStateException if the heap is empty.
*/
T remove() {
if (size == 0) {
throw new IllegalStateException();
}
Comparable root = data[0];
data[0] = data[size-1];
size--;
trickleDown(0);
return (T) root;
}
private void trickleDown(int i) {
int largerChild;
Comparable top = data[i]; // save root
while(i > size/2 ) // not on bottom row{
int leftChild = left(i);
int rightChild = right(i);
if(rightChild > size && data[left(i)].compareTo(data[right(i)]) < 0 )
largerChild = leftChild;
else
largerChild = rightChild;
if(data[i].compareTo(data[right(i)]) <= 0 )
break;
data[i] = data[largerChild];
i = largerChild;
}
data[i] = top;
}
///// Test File
void checkHeapOrder(MinHeap h) {
assertTrue(h != null);
for(int i = 1; i < h.size() / 2; ++i)
assertTrue("Heap order property is broken at element at position "
+ i,
h.data[i].compareTo(h.data[i*2]) < 0 &&
h.data[i].compareTo(h.data[i*2 + 1]) < 0);
}
#Test
public void testRemove() {
System.out.println("remove");
MinHeap h = new MinHeap(10);
boolean throws_exception = false;
try {
h.remove();
} catch (IllegalStateException e) {
throws_exception = true;
} catch (Throwable e) {
}
assertTrue("remove throws an exception when empty", throws_exception);
// Permutation of 0...9
int[] input = { 0, 5, 9, 2, 3, 1, 6, 8, 7, 4 };
for(int i : input)
h.insert(i);
assertTrue(h.isFull());
for(int i = 10; i > 0; --i) {
assertEquals(h.size(), i);
Integer x = (Integer)h.remove();
assertEquals(x, new Integer(10-i)); // Items are removed in correct order
checkHeapOrder(h);
}
testRemove Failed: expected<0> but was <1>
I am pretty sure that the code is simple and i have tried to change everything from max to min,but just missing on with something,which i am having a hard time figuring out.
You can find ArrayLinearLists from here in EPROGS Trying to sort a datas from .txt file into three different ArrayLinearLists. But the problem is about their capacity. Whenever the .add function is called the capacity is doubled.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String line;
int indexOfCode = 0;
int indexOfName = 1;
int indexOfCredit = 2;
int count = 0;
ArrayLinearList codeR = new ArrayLinearList();
ArrayLinearList nameR = new ArrayLinearList();
ArrayLinearList creditR = new ArrayLinearList();
try (BufferedReader br = new BufferedReader(new FileReader("Subjects.txt"))) {
while ((line = br.readLine()) != null) {
String values[] = line.split("/");
codeR.add(0, values[indexOfCode]);
nameR.add(0, values[indexOfName]);
creditR.add(0, values[indexOfCredit]);
}
System.out.println(codeR);
System.out.println(nameR);
System.out.println(creditR);
}
}
}
Here is the ArrayLinearList codes
protected Object[] element; // array of elements
protected static int size; // number of elements in array
protected static ArrayLinearList theObject;
// constructors
/**
* create a list with initial capacity initialCapacity
*
* #throws IllegalArgumentException
* when initialCapacity < 1
*/
public ArrayLinearList(int initialCapacity) {
if (initialCapacity < 1)
throw new IllegalArgumentException("initialCapacity must be >= 1");
// size has the default initial value of 0
element = new Object[initialCapacity];
}
/** create a list with initial capacity 10 */
public ArrayLinearList() {// use default capacity of 10
this(10);
}
// methods
/** #return true iff list is empty */
public boolean isEmpty() {
return size == 0;
}
/** #return current number of elements in list */
public int size() {
return size;
}
/**
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
void checkIndex(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
}
/**
* #return element with specified index
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
public Object get(int index) {
checkIndex(index);
return element[index];
}
/**
* #return index of first occurrence of theElement, return -1 if theElement
* not in list
*/
public int indexOf(Object theElement) {
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}
/**
* Remove the element with specified index. All elements with higher index
* have their index reduced by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
* #return removed element
*/
public Object remove(int index) {
checkIndex(index);
// valid index, shift elements with higher index
Object removedElement = element[index];
for (int i = index + 1; i < size; i++)
element[i - 1] = element[i];
element[--size] = null; // enable garbage collection
return removedElement;
}
/**
* Insert an element with specified index. All elements with equal or higher
* index have their index increased by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size
*/
public void add(int index, Object theElement) {
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
// valid index, make sure we have space
if (size == element.length)
// no space, double capacity
element = ChangeArrayLength.changeLength1D(element,2* size);
// shift elements right one position
for (int i = size - 1; i >= index; i--)
element[i + 1] = element[i];
element[index] = theElement;
size++;
}
/** convert to a string */
public String toString() {
StringBuffer s = new StringBuffer("[");
// put elements into the buffer
for (int i = 0; i < size; i++)
if (element[i] == null)
s.append("null, ");
else
s.append(element[i].toString() + ", ");
if (size > 0)
s.delete(s.length() - 2, s.length()); // remove last ", "
s.append("]");
// create equivalent String
return new String(s);
}
/** create and return an iterator */
public Iterator iterator() {
return new ArrayLinearListIterator((MyArrayList) this);
}
/** test program */
public static void main(String[] args) {
// test default constructor
LinearList x = new ArrayLinearList();
// test size
System.out.println("Initial size is " + x.size());
// test isEmpty
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
// test put
x.add(0, new Integer(2));
x.add(1, new Integer(6));
x.add(0, new Integer(1));
x.add(2, new Integer(4));
System.out.println("List size is " + x.size());
// test toString
System.out.println("The list is " + x);
// test indexOf
int index = x.indexOf(new Integer(4));
if (index < 0)
System.out.println("4 not found");
else
System.out.println("The index of 4 is " + index);
index = x.indexOf(new Integer(3));
if (index < 0)
System.out.println("3 not found");
else
System.out.println("The index of 3 is " + index);
// test get
System.out.println("Element at 0 is " + x.get(0));
System.out.println("Element at 3 is " + x.get(3));
// test remove
System.out.println(x.remove(1) + " removed");
System.out.println("The list is " + x);
System.out.println(x.remove(2) + " removed");
System.out.println("The list is " + x);
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
System.out.println("List size is " + x.size());
}
}
And thanks in advance ,great senior developers :D
For a developer using ArrayLinearList this means giving a larger initial capacity, to prevent too many increases.
Using an estimate:
Path path = Paths.get("Subjects.txt");
int initialCapacity = (int)(Files.size(path) / 3);
For a developer implementing ArrayLinearList heshe could pick a larger default initial capacity, or something like increasing the array size by 1000 + array.length/4, to not waiste as much space, and initially have not so many repeated increases.
My program doesn't show each of the correct list it's being sorted, number of comparison and number of assignment except bubble sorting method. I think I missed to reset the input string but could not figure out the way to reset input.
Is there any way to sort one input in different sorting method.
Here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
/**
* Create a program that does head-to-head comparisons between four sorting
* methods: improved bubble sort; selection sort; insertion sort; and Shell
* sort.
*
*/
public class SortAlgorithms {
private static char tracing;
private static char list;
private static int numAsgn = 0;
private static int numComp = 0;
private static int size;
private static int min;
private static int max;
private static final Scanner KBD = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements do you want in the list? ");
size = KBD.nextInt();
System.out.print("What are the smallest and largest values for lsit elements? ");
min = KBD.nextInt();
max = KBD.nextInt();
KBD.nextLine();
pause();
System.out.print("Would you like to see the list before it's sorted? ");
list = Character.toUpperCase(br.readLine().charAt(0));
System.out.print("Would you like to see the list as it's being sorted? ");
tracing = Character.toUpperCase(br.readLine().charAt(0));
pause();
sortNumbers();
}
// prompt the user and wait for them to press enter
private static void pause() {
System.out.print("\n...Press enter...");
KBD.nextLine();
System.out.println();
}
/**
* Sort a list of integer values, generated randomly.
*/
public static void sortNumbers() {
resetCounts();
Integer[] numbers = randomNumbers(size, min, max);
if (list == 'Y') {
System.out.println("Here is the list: " + Arrays.toString(numbers));
pause();
}
System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");
bubbleSort(numbers);
System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);
selectionSort(numbers);
System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);
insertionSort(numbers);
System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);
shellSort(numbers);
System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);
}
/**
* Reset the operation counts to zero.
*/
public static void resetCounts() {
numAsgn = 0;
numComp = 0;
}
/**
* Generate an array of random values.
*
* #param howMany the length of the list to be generated.
* #param lo the smallest value allowed in the list
* #param hi the largest value allowed in the list
*/
public static Integer[] randomNumbers(int size, int min, int max) {
int range = max - min + 1;
Integer[] result = new Integer[size];
for (int i = 0; i < size; ++i) {
result[i] = (int) (min + range * Math.random());
}
return result;
}
/**
* Perform bubble sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void bubbleSort(T[] a) {
for (int i = a.length - 1; i > 0; --i) {
boolean elementSwapped = false;
//numComp++;
for (int j = 0; j < i; ++j) {
numComp++;
if (a[j].compareTo(a[j + 1]) > 0) {
numAsgn += 3;
T temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
elementSwapped = true;
}
}
if (!elementSwapped) {
break;
}
//if (tracing == 'Y') {
System.out.println("one more bubbled up: "
+ Arrays.toString(a));
//}
}
}
/**
* Perform insertion sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void insertionSort(T[] a) {
for (int i = 0; i < a.length - 1; ++i) {
int p = i + 1;
T temp = a[p];
++numAsgn;
while (p > 0 && a[p - 1].compareTo(temp) > 0) {
++numComp;
a[p] = a[p - 1];
++numAsgn;
--p;
}
if (p > 0) {
++numComp; // count the last a[p-1] comparison
}
a[p] = temp;
++numAsgn;
//if (tracing == 'Y') {
System.out.println("one more inserted: " + Arrays.toString(a));
//}
}
}
/**
* Perform selection sort on the given array. if tracing, show the array
* after each selection round.
*
* #param a the array to sort
*/
public static <T extends Comparable<? super T>>
void selectionSort(T[] a) {
for (int i = 0; i < a.length - 1; ++i) {
int p = i;
++numAsgn;
for (int j = i + 1; j < a.length; ++j) {
++numComp;
if (a[j].compareTo(a[p]) < 0) {
p = j;
++numAsgn;
}
}
T temp = a[i];
a[i] = a[p];
a[p] = temp;
++numAsgn;
//if (tracing == 'Y') {
System.out.println("one more selected: " + Arrays.toString(a));
//}
}
}
/**
* Perform shell sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void shellSort(T[] a) {
int gap = a.length / 2;
++numComp;
while (gap >= 1) {
if (gap % 2 == 0) {
++gap;
}
++numComp;
for (int i = gap; i < a.length; ++i) {
++numAsgn;
int p = i;
T temp = a[p];
++numComp;
while (p >= gap && a[p - gap].compareTo(temp) > 0) {
a[p] = a[p - gap];
p -= gap;
++numAsgn;
}
a[p] = temp;
++numAsgn;
}
//if (tracing == 'Y') {
System.out.println("...gap=" + gap + ": " + Arrays.toString(a));
// }
gap /= 2;
}
}
/**
* Calculate how many operations a list of the given length should take.
*
* #param numItems the number of elements in a list.
* #return the number of operations expected (on average) to sort that list
*/
private static int expect(int numItems) {
return (numItems * numItems + numItems) * 5 / 4;
}
}
You are overriding array numbers each time you sort, so since bubbleSort is the first sorting method, you only get to see that one. Each consecutive sorting method just operates on a sorted array. Also since you've defined your counts as member variables, you need to call resetCounts() right before each method to get a fresh count. Making a copy of the array before you pass it to each sorting method, and resetting the counts should fix this.
System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");
resetCounts();
bubbleSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);
resetCounts();
selectionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);
resetCounts();
insertionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);
resetCounts();
shellSort(numbers);
System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);
I am experiencing an error. Running this program requires referencing the compiled jar file in a command line to specify the targets that must be found in the input file.
The error that is happening is any target string specified in the command line (that is present in the input file) gets an output of " not found", when it should be outputting " found on line {lineNumber}".
I went through the entirety of the class and frankly, I'm completely lost as to where this error occurs.
Any help is appreciated.
Main Class:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Search {
public static void main(String[] args) throws FileNotFoundException {
Scanner in = null;
int index = 0;
String[] word = null;
int[] lineNumber = null;
// check number of command line arguments is at least 2
if (args.length < 2) {
System.out.println("Usage: Search <input file> <target1> [target2...]");
System.exit(1);
}
// initialize Scanner
in = new Scanner(new File(args[0]));
// matches the end of a file character
in.useDelimiter("\\Z");
// puts entire file into one string
String temp = in.next();
in.close();
// intialize arrays & plug elements in
word = temp.split("\n");
lineNumber = new int[word.length];
populate(lineNumber);
// sort String array
mergeSort(word, lineNumber, 0, word.length - 1);
// if multiple targets exist
if (args.length > 2) {
for (int i = 1; i < args.length; i++) {
index = binarySearch(word, 0, word.length - 1, args[i]);
if (index < 0) {
System.out.println(args[i] + " not found");
} else {
System.out.println(args[i] + " found on line " + lineNumber[index]);
}
}
// if only single target specified in command line
} else {
index = binarySearch(word, 0, word.length - 1, args[1]);
if (index < 0) {
System.out.println(args[1] + " not found");
} else {
System.out.println(args[1] + " found on line " + lineNumber[index]);
}
}
}
// recursively halves arrays then plugs into merge function
public static void mergeSort(String[] word, int[] lineNumber, int p, int r) {
int q;
if (p < r) {
// q is midpoint
q = (p + r) / 2;
// recursive stuff
mergeSort(word, lineNumber, p, q);
mergeSort(word, lineNumber, q + 1, r);
// merge arrays
merge(word, lineNumber, p, q, r);
}
}
// merges sorted String arrays into one large sorted String array
public static void merge(String[] word, int[] lineNumber, int p, int q, int r) {
// element ranges
int n1 = q - p + 1;
int n2 = r - q;
// half String arrays to be merged
String[] L = new String[n1];
String[] R = new String[n2];
// half int arrays to be merged
int[] iL = new int[n1];
int[] iR = new int[n2];
// array indexes (for looping)
int i, j, k;
// plugging specific elements into new array
for (i = 0; i < n1; i++) {
L[i] = word[p + i];
iL[i] = lineNumber[p + i];
}
// plugging specific elements into new array
for (j = 0; j < n2; j++) {
R[j] = word[q + j + 1];
iR[j] = lineNumber[q + j + 1];
}
// reset array indexes
i = 0;
j = 0;
// loop through entirety of elements
for (k = p; k <= r; k++) {
// if both arrays still have unmerged element(s)
if (i < n1 && j < n2) {
// if left array's element precedes right's element
// lexicographically
if (L[i].compareTo(R[j]) < 0) {
word[k] = L[i];
lineNumber[k] = iL[i];
i++;
} else { // if right's element precedes (or the words are equal)
word[k] = R[j];
lineNumber[k] = iR[j];
j++;
}
// if only left array has unmerged element(s)
} else if (i < n1) {
word[k] = L[i];
lineNumber[k] = iL[i];
i++;
// if only right array has unmerged element(s)
} else {
word[k] = R[j];
lineNumber[k] = iR[j];
j++;
}
}
}
// searches sorted String array and returns index of target (or -1 if not
// found)
public static int binarySearch(String[] word, int p, int r, String target) {
int q;
if (p > r) {
return -1;
} else {
q = (p + r) / 2;
if (target == word[q]) {
return q;
} else if (target.compareTo(word[q]) < 0) {
return binarySearch(word, p, q - 1, target);
} else {
return binarySearch(word, q + 1, r, target);
}
}
}
// helper method: plugs numbers (in order) into an int array
public static void populate(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i + 1;
}
}
}
You need to change the below method. String should be compared with equals() method and use trim() method to avoid trailing spaces.
public static int binarySearch(String[] word, int p, int r, String target) {
int q;
if (p > r) {
return -1;
} else {
q = (p + r) / 2;
if (target.trim().equals(word[q].trim())) {
return q;
} else if (target.compareTo(word[q]) < 0) {
return binarySearch(word, p, q - 1, target);
} else {
return binarySearch(word, q + 1, r, target);
}
}
}
I created my own implementation of merge sort, I tested it that it works. How ever I am not sure if it's O(N Log(N)) as it should be, or it's O(N^2), can you please look at my code and tell?
SortedList
public abstract class SortedList {
public final ArrayList<Integer> params = new ArrayList<Integer>();
public void add(int... params) {
for (int parameter : params) {
this.params.add(parameter);
}
}
abstract public void sort();
public void print() {
for (int parameter : params) {
System.out.print(parameter + " ");
}
System.out.println();
}
}
MargeSort
public class MargeSort extends SortedList{
private int buffer[];
#Override
public void sort() {
buffer = new int[params.size()];
for(int i = 1; i < params.size(); i *= 2){
sort(i);
}
}
private void sort(int interval) {
for(int i = 0; i < params.size() - interval; i += interval * 2){
sort(i, i + interval, interval);
}
}
private void sort(int index1, int index2, int interval) {
int startingIndex = index1;
int index1MaxValue = index1 + interval;
int index2MaxValue = index2 + interval;
if(index2MaxValue >= params.size()){
index2MaxValue = params.size();
}
int counter = 0;
for(counter = 0; index1 < index1MaxValue && index2 < index2MaxValue; counter++){
int param1 = params.get(index1);
int param2 = params.get(index2);
if(param1 < param2){
buffer[counter] = param1;
index1++;
}
else{
buffer[counter] = param2;
index2++;
}
}
int index, indexMaxValue;
if(index1 < index1MaxValue){
index = index1;
indexMaxValue = index1MaxValue;
}
else{
index = index2;
indexMaxValue = index2MaxValue;
}
while(index < indexMaxValue){
int param = params.get(index);
buffer[counter] = param;
index++;
counter++;
}
for(int i = 0; i < interval * 2 && i + startingIndex < params.size(); i++){
params.set(i + startingIndex, buffer[i]);
}
}
}
sort(int) is called lg N times, where N = params.size(). [lg N here and everywhere further means ceil(lg N)]
Loop in sort(int) loops N / (interval / 2) times, where interval in [1 .. lgN], calling sort(...), which takes nr of steps, which is lineary depends on its' interval arg.
So, nr of steps is:
Sigma(k in from 1 to lgN): (N / (interval / 2)) * (C * interval) = C * N/2 * Sigma(1..lgN) 1 = C * N * lgN /2
[ C is constant for accounting of inner sort(...) cost ]