In the main, whenever I call this method to sort the array, it stops as if it's waiting for a response. Any idea why it's not working?
public void bubbleSort(){
boolean finished = false;
boolean swapOccurred = false;
int i = 0;
int next = i + 1;
while (finished == false)
{
for (; i < theArray.length - 1; i++)
{
if (theArray[i] > theArray[next])
{
swapValues(theArray[i], theArray[next]);
swapOccurred = true;
}
}
if (swapOccurred == false)
{
finished = true;
}
}
}
private void swapValues(int i, int next) {
int temp;
temp = i;
i = next;
next = temp;
}
If it is java, then
The next index is never updated so it stays 1 all the time.
The swap method has no side effect, you want to swap the elements in theArray, but in java methods arguments are passed as values so the next and i variables change the value only inside the swap method, they have nothing to do with the cells of theArray array.
The problem is with your swap.
In C, arguments are passed by value, so when you do the swap, the values being passed in aren't affected, so nothing is happening. You need to pass in pointers to the numbers instead (and then dereference them inside):
private void swapValues(int *i, int *next) {
int temp;
temp = *i;
*i = *next;
*next = temp;
}
And then call it with the address of the variables to swap:
swapValues(&theArray[i], &theArray[next]);
Edit: Ha - #Zielu saw Java, I saw C. Same problem in both cases, and as #Zielu points out, you also need to increment next. I believe you actually just want to use [i+1] as your index in place of next.
Related
Where is "int size " getting it's value from? I read code like 1000 times,but I still have no clue where is "size" initialized, I am new in java, but I don't understand this one,code is working fine any help would be nice. thanks in advance
public class Study {
public static void main(String[] args) {
Queue queue = new Queue();
for (int i = 0; i <= 20; i++)
queue.enqueue(i);
while (!queue.empty())
System.out.print(queue.dequeue() + " ");
}
}
class Queue {
private int[] elements;
private int size;
public Queue() {
elements = new int[8];
}
public void enqueue(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
System.out.println(elements.length);
elements = temp;
}
elements[size++] = value;
}
public int dequeue() {
int v = elements[0];
// Shift all elements in the array left
for (int i = 0; i < size - 1; i++) {
elements[i] = elements[i + 1];
}
size--;
return v;
}
public boolean empty() {
return size == 0;
}
public int getSize() {
return size;
}
}
Default value is 0 for int.
And size++ and size-- is doing the changes to its value.
For more information refer: Assignment, Arithmetic, and Unary Operators
size++ is equal to the statement size = size + 1, the same for size-- which does size = size - 1
All instance variables will be assigned a default value by the compiler if you haven't provided one.
Snippet from java doc
Default value will be zero or null depending the data types.
The link also has a grid which tells you about the default values for all data types.
Local variables are variables which are used inside a method:
The compiler never assigns a default value to an uninitialized local
variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.
This is a follow-up to my previous question that I asked yesterday. I wrote a Bubble Sort method that analyzes an array of strings and returns the NUMBER of comparisons that the method has made when ordering the array into alphabetical order (the assignment is to write several types of sorting methods and graph the number of comparisons each one makes, to see which is most efficient).
This is my code:
public static void main(String[] args)
{
String[] test_array = {"bill", "phil", "adam"};
/*
System.out.println(compare("orange", "boogie"));
*/
System.out.println(bubbleSort(test_array));
}
public static int compare(String a, String b)
{
int len = Math.min (a.length(),b.length());
// looping through every character. If cha is less than chb, the method returns -1, and so on.
for (int i = 0; i<len; i++) {
char cha = a.charAt(i);
char chb = b.charAt(i);
if (cha < chb) {
return -1;
} else if (cha > chb) {
return 1;
}
}
// Now we account for the length of the word, since it could be the same word.
if (a.length() < b.length())
return -1;
else if (a.length() > b.length())
return 1;
// Seems to be the same String, so return 0.
else
return 0;
}
public static int bubbleSort(String[] test_array) {
boolean swapped = true;
// Variable to track number of comparisons.
int compNumber = 0;
while (swapped == true) {
swapped = false;
for (int i = 1; i < test_array.length; i++) {
// Tracking the number of comparisons
compNumber++;
if (compare(test_array[i-1], test_array[i]) > 0) {
//Switching the variables by use of a temp variable
String temp = test_array[i-1];
test_array[i-1] = test_array[i];
test_array[i] = temp;
swapped = true;
}
else {
swapped = true;
}
}
}
return compNumber;
}
So the compare method compares two strings (given by the array) and determines if they are in alphabetical order (returns -1) or not (returns 1), or is the same word (returns 0). Then, the bubble sort method calls upon the compare method to go through the array, and it then makes the switches, while my compNumber variable counts the number of times the loop (therefore the number of comparisons) runs.
It compiles fine, but it unfortunately doesn't stop running and doesn't return anything. I've waited 5 minutes so I've determined that something is wrong, probably with my loops. I can't seem to find an issue, having manipulated the parameters of the loops several times. Could anyone help me out? Thanks in advance.
"swapped" will always be true, hence the while will never end looping.
I think you meant to put swapped = false in the else statement
you need to set one of these two swapped = false... or else you will never exit the while loop because swapped = true always ... probably changing the second one makes sense !
if (compare(test_array[i-1], test_array[i]) > 0) {
//Switching the variables by use of a temp variable
String temp = test_array[i-1];
test_array[i-1] = test_array[i];
test_array[i] = temp;
swapped = true;
}
else {
swapped = true;
}
I have an array of objects and i want to add elements in this array and simultaneously sort them in ascending order.Although I tried many compinations , I always take a java.lang.ArrayIndexOutOfBoundsException. Here is a part of my code :
public boolean insert(Person p)
{
for(int i=0;i<=size();i++)
{
if (c==0)
{
array[0] = p;
c++;
return true;
}
else
{
if (p.compareTo(array[i])==-1)
{
array[i]=p;
c++;
for(int j = size(); j>i; j--)
{
array[j]=array[j-1];
}
}
else if((p.compareTo(array[i])==1))
{
array[i+1]=p;
c++;
for (int j=(size()-1);j>= i+1; j--)
{
array[j+1]=array[j];
}
}
else
{
return false;
}
return true;
}
}
return false;
}
private int c;
private Person array[];
public SortedPersonList()
{
this.array = new Person[c];
}
public int size()
{
return c;
}
Remove the equal sign in for(int i=0;i<=size();i++). That is, change to
for(int i=0;i<size();i++)
Array indices go from 0 to size-1. So array[size()] is outside the array. Hence the error.
1) You are initializing your array to a size 0, and you never resize it. An array has a fixed size, so in order to populate it with items beyond its range, you should first create a larger array and copy the contents to it (This is how ArrayList works).
2) When you find the insertion point, you shouldn't override this position before keeping its value in a temp variable. (Also, I don't understand the third case in your code. Why do you insert if p is greater than array[i]? you should rethink your logic.)
3) you may want to use binary search to find the insertion point. It has a better performance than linear search.
Your code :
for(int i=0;i<=size();i++)
Write like
for(int i=0;i<size();i++) or for(int i=0;i<=size()-1;i++)
I am just consfused on how to implement these two methods like how call them or use them? Since the first one is void how does it work?
someone please use and an array and implement this for me or help me understand how the first void method works?
public static void insertionsort(int[] numbers) {
for (int i = 0; i < numbers.length; i++) {
int copyNumber = numbers[i];
int j = i;
while (j > 0 && copyNumber < numbers[j-1]) {
numbers[j] = numbers[j-1];
j--;
}
numbers[j] = copyNumber;
}
}
public int[] InsertionSort(int[] data){
int len = data.length;
int key = 0;
int i = 0;
for(int j = 1;j<len;j++){
key = data[j];
i = j-1;
while(i>=0 && data[i]>key){
data[i+1] = data[i];
i = i-1;
data[i+1]=key;
}
}
return data;
}
A function with return type does something (executes code) and returns some result back to the code that called that function. A function without return type executes some code but does not return a result ( because it is not needed in most cases )
Consider this two functions:
public static int withResult( int someParameter)
{
//execute some code here
int someReturnValue = //result of the code above
return someReturnValue;
}
public static void withoutResult( int someParameter)
{
//execute some code here which produces no result which could be of interest to the caller (calling code)
} //end the function without returning anything
You would call it like this:
int result;
result = withResult( 1234 );//executes the function and stores its return type in 'result'
withResult( 468 );//executes the function but does not store the return type anywhere ("throws it away")
withoutResult ( 1234 );//simply executes the function
result = withoutResult ( 5678 ); //this makes no sense because the function does not return anything
In java everything is passed by value, including references. In your void method, the value of a reference to the array is passed. So while you cannot assign a new int [] to numbers, you are able to change the ints in numbers.
The first method, returning void (i.e., not returning anything) is passed an array as a parameter. What is passed is a reference to an array that is declared and for which memory is allocated outside the method. The method sorts that information in place; when the method returns, the data in that array is then sorted.
int[] myArray = getArrayInfo(); // assume this gets data in an array
WhateverClass.insertionSort(myArray); // this will sort that data
// at this point, myArray will be sorted
Currently working on a java program that does a bunch of functions, and one of those functions is to delete a range of alphabetized words. I am using animals as an example.
Here is the display list prior to executing the deleteRange function:
cat
chinchilla
horse
mouse
rat
I ask the program to delete chinchilla to mouse, but it doesn't include horse.
public boolean deleteRange(String start, String stop){
boolean result = false;
int begin = Find(start);
int end = Find(stop);
while(begin<end){
Delete(storage[begin]);
begin++;
result = true;
}
return result;
}
My delete function:
public boolean Delete(String value){
boolean result = false;
int location;
location = Find(value);
if (location >= 0) {
moveItemsUp(location);
numUsed--;
result = true;
}
return result;
}
My find function:
public int Find(String value) {
int result = -1;
int index = 0;
boolean found = false;
while ((index < numUsed) && (!found)) {
found = (value.equals(storage[index]));
if (!found)
index++;
}
if (found)
result = index;
return result;
}
My moveitemsup function:
private void moveItemsUp(int start){
int index;
for (index = start; index < numUsed-1; index++){
storage[index] = storage[index+1];
}
}
So, you are deleting array indices 1 -3 --
After you delete array index 1, your former index 3 now becomes 2 AND you are incrementing "begin" .. So now you delete index 2.. which in this case is mouse .. so horse gets skipped .
Instead, you want to keep the number of elements to delete ( end - begin + 1 )
int count = end - begin + 1;
while ( count > 0 ) {
Delete(storage[begin]);
}
something along those lines.
Why don't you try something like this if your list is in an ArrayList (no Java stuff on this box so this hasn't been tested) .
public boolean deleteRange( String start, String stop ) {
for(Iterator<String> iter = storage.iterator();iter.hasNext();) {
String element = iter.next();
if(element.compareTo(start) >= 0 && element.compareTo(stop) <= 0 ) {
iter.remove();
}
}
}
The problems I can see are:
problem 1
you increase begin index and "shrink (not really shrink)" the array at same time, after each deletion.
for example
[a,b,c,d,e,f], say you want to delete b-e index 1-4
first you deleted b (index 1) then you moveItemsUp after deletion. so array is:
[a,c,d,e,f,f], then you begin++ begin is 2, which pointing d, jumped over c
problem 2
if you fixed problem 1, there is another thing you should consider about, after deletion, the array would be [a,f,f,f,f,f] if it is what you wanted.
btw, why not consider to use LinkedList ? it should be much faster for deletion.
int begin = Find(start);
int end = Find(stop);
int count = end - begin;
for (int i=0; i <= count; i++){
Delete(storage[begin]);
result = true;
changed some code to this, made it work =)