Int array sorting itself - java

import java.util.ArrayList;
public class Paaohjelma {
public static int pienin(int[] taulukko) {
int temp, size;
size = taulukko.length;
for(int i = 0; i<size; i++ ){
for(int j = i+1; j<size; j++){
if(taulukko[i]>taulukko[j]){
temp = taulukko[i];
taulukko[i] = taulukko[j];
taulukko[j] = temp;
}
}
}
return taulukko[0];
}
public static int pienimmanIndeksi(int[] taulukko) {
ArrayList<Integer> tauli = new ArrayList<>();
for (int i : taulukko) {
tauli.add(i);
}
return tauli.indexOf(Paaohjelma.pienin(taulukko));
}
public static int pienimmanIndeksiAlkaen(int[] taulukko, int aloitusIndeksi) {
// this methods should get the index of smallest value starting from specified index
int[] tempTauli = taulukko;
tempTauli = new int[tempTauli.length - aloitusIndeksi];
// this gets the right values to temporary array
if (aloitusIndeksi > 0) {
int index = 0;
int indexTauli = 0;
for(int value : taulukko) {
if(index >= aloitusIndeksi) {
tempTauli[indexTauli] = taulukko[index];
indexTauli++;
}
index++;
}
}
// values added are automatically sorted from smallest to largest?
// this shouldn't be, array should be 5, 99, 3, 12 but is shown as 3, 5, 12, 99
for(int inty : tempTauli) {
System.out.println(inty);
}
// get the index of smallest value in array
// index is 0 should be 2
int index = Paaohjelma.pienimmanIndeksi(tempTauli);
// return index of smallest value (add starting index to get the index of smallest value in the original array when starting from specified index)
return index+aloitusIndeksi;
}
public static void main(String[] args) {
// test code
int[] taulukko = {3, 1, 5, 99, 3, 12};
int minIndex = Paaohjelma.pienimmanIndeksi(taulukko);
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
System.out.println("Pienimmän indeksi: " + minIndex);
System.out.println(Paaohjelma.pienimmanIndeksiAlkaen(taulukko, 2));
}
}
Hello! I'm doing some programming course work for school and have been stuck in this particular part for couple hours. So I decided it would be best for someone else to take a look and provide some light why my approach for this problem isn't working.
What should happen: class method PienimmanIndeksiAlkaen should return the index of smallest value in provided int array starting from specified index.
The main problem I have been having is that the array seems to be automatically sorting itself and I have no idea what is possible causing this. I have commented the relevant part of the code and would be more than happy if someone could explain why this is happening and what possible could be done to prevent this.

The reason your array is sorted is when you call
System.out.println("Pienin: " + Paaohjelma.pienin(taulukko));
you sort the array.
When you pass the array into this function, you aren't actually passing the value of the array, but the pointer to the array - the address of the array in memory. This is the difference between passing parameters by value or by reference.
How do you know if the value is passed by value or by reference?
As a rule of thumb:
primitive values - i.e. int, double, etc. will be passed by value - their value will be copied and passed to the function.
Any other type, namely arrays and classes, will be passed by reference - the address of the value in memory will be passed to the function, thus any change to the value inside the function will affect it when the function ends too.
Read more here

Related

Why this below code is not returning the desired output ? it should return 1,3,2,2,0,0,0 while its returning same array

When I run the below code it's returning same array as output. Can anyone tell me where I am wrong?
public class MoveZeroToend {
public static void main(String[] args) {
int[] arr = { 1, 3, 0, 2, 0, 2, 0 };
Move0Toend(arr);
}
static void Move0Toend(int[] arr) { // Code to move zeroes to end
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != 0) {
swap(arr[i], arr[count]);
count++;
}
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " "); // Print the array
}
}
static void swap(int a, int b) { // To swap
a = a + b;
b = a - b;
a = a - b;
}
}
on your swap method, you are not swapping the actual values of the objects you've passed, you are swapping between the values passed to the method but there is no result returned so nothing happens. you need to either do the swap on the actual objects - not in a method, or use another way for this. I would recommend googling "pass by value" and "pass by reference". I would also recommend adding a unit test or at least debug the program so you can validate your code is doing what you want.
Your swap method doesn't return any values, nor does it change the values in the reference of the objects passed. To fix this you can either return two values from your swap method (a and b) or you could do it not in a method, that way it would directly affect the objects.
Just for a little more explanation, the variables a and b in your swap method are local to the swap method, changing these would not affect any other variables, even if they were also named the same, and as your method is a void it can't return anything.
Hope this helps :)
Your swap() method isn't performing any operation on your array, you are just passing two values a and b and swapping them but no operation is being performed on your array.
Instead of passing these two values to your swap() method you can directly swap them inside your for loop as below:
for(int i=0;i<arr.length;i++){
if(arr[i]!=0){
int temp = arr[i];
arr[i] = arr[count];
arr[count] = temp;
count++;
}
}

Adding elements to the beginning of an array of ints

Working on an addBefore() method that adds a new element to the beginning of an array of ints and then causes the existing elements to increase their index by one.
This is what is showing in the console when trying to run --
java.lang.RuntimeException: Index 1 should have value 11 but instead has 0
at IntArrayListTest.main(IntArrayListTest.java:67)
Below is the code I have so far.
public class IntArrayList {
private int[] a;
private int length;
private int index;
private int count;
public IntArrayList() {
length = 0;
a = new int[4];
}
public int get(int i) {
if (i < 0 || i >= length) {
throw new ArrayIndexOutOfBoundsException(i);
}
return a[i];
}
public int size() {
return length;
}
public void set(int i, int x) {
if (i < 0 || i >= a.length) {
throw new ArrayIndexOutOfBoundsException(i);
}
a[i] = x;
}
public void add(int x) {
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
a = b;
//count += 1;
}
a[length] = x;
count++;
length = length + 1;
}
public void addBefore(int x) {
int[] b = new int[a.length*2];
for (int i = 0; i < a.length; i++) {
b[i+a.length] = a[i];
}
a = b;
a[index] = x;
length ++;
}
}
Whether you add first or last, you need to only grow the array size if it is already full.
The count field seems to be exactly the same as length, and index seems unused and meaningless as a field, so remove them both.
To rearrange values in an array, use this method:
System.arraycopy(Object src, int srcPos, Object dest, int destPos, int length)
You two "add" methods should then be:
public class IntArrayList {
private int[] a; // Underlying array
private int length; // Number of added elements in a
// other code
public void add(int x) {
if (length == a.length) {
int[] b = new int[a.length * 2];
System.arraycopy(a, 0, b, 0, length);
a = b;
}
a[length++] = x;
}
public void addBefore(int x) {
if (length < a.length) {
System.arraycopy(a, 0, a, 1, length);
} else {
int[] b = new int[a.length * 2];
System.arraycopy(a, 0, b, 1, length);
a = b;
}
a[0] = x;
length++;
}
}
If the answer requires you to do the looping yourself then something like this should work fine (one of a few ways to do this, but is O(n)) :
public void addBefore(int x) {
if(length + 1 >= a.length){
int[] b = new int[a.length*2];
b[0] = x;
for (int i = 0; i < length; i++) {
b[i + 1] = a[i];
}
a = b;
} else {
for (int i = length; i >= 0 ; i--) {
a[i + 1] = a[i];
}
a[0] = x;
}
length++;
}
I noticed this started running a "speed test" - not sure how useful a test like that is, as it would be based on cpu performance, rather than testing complexity of the algorithm ..
you had three problems with your solution:
you increased the length of a every time the method was called. this would quickly create an OutOfMemoryException
when you copied values from a to b, you did b[i+a.length] = a[i]; which means the values would be copied to the middle of b instead of shift just one place
at the end, you put the new value in the end of the array instead of at the beginning.
all this I was able to see because I used a debugger on your code. You need to start using this tool if you want to be able to detect and fix problems in your code.
so fixed solution would do this:
check if a is full (just like it is done with add() method) and if so, create b, and copy everything to it and so on)
move all values one place ahead. the easiest way to do it is to loop backwards from length to 0
assign new value at the beginning of the array
here is a working solution:
public void addBefore(int x) {
// increase length if a is full
if (length >= a.length) {
int[] b = new int[a.length * 2];
for (int i = 0; i < a.length; i++) {
b[i] = a[i];
}
a = b;
}
// shift all values one cell ahead
for (int i = length; i > 0; i--) {
a[i] = a[i-1];
}
// add new value as first cell
a[0] = x;
length ++;
}
}
You can use the existing Java methods from the Colt library. Here is a small example that uses a Python syntax (to make the example code small I use Jython):
from cern.colt.list import IntArrayList
a=IntArrayList()
a.add(1); a.add(2) # add two integer numbers
print "size=",a.size(),a
a.beforeInsert(0, 10) # add 10 before index 0
print "size=",a.size(),a
You can use DataMelt program to run this code. The output of the above code is:
size= 2 [1, 2]
size= 3 [10, 1, 2]
As you can see, 10 is inserted before 1 (and the size is increased)
Feel free to change the codding to Java, i.e. importing this class as
import cern.colt.list.IntArrayList
IntArrayList a= new IntArrayList()
You could use an ArrayList instead and then covert it to an Integer[] Array which could simplify your code. Here is an example below:
First create the ArrayList:
ArrayList<Integer> myNums = new ArrayList<Integer>();
Next you can add the values that you want to it, but I chose to just add the numbers 2-5, to illustrate that we can make the number 1 the first index and automatically increment each value by one index. That can simplify your addBefore() method to something such as this:
public static void addBefore(ArrayList<Integer> aList) {
int myInt = 1;
aList.add(0, myInt);
}
Since your ArrayList has ONE memory location in Java, altering the Array within a method will work (this would also work for a regular Array). We can then add any value to the beginning of the ArrayList. You can pass an Integer to this method as the second argument (int x), if you want, but I simply created the myInt primitive to simplify the code. I know that in your code you had the (int x) parameter, and you can add that to this method. You can use the ArrayList.add() method to add the int to index 0 of the Array which will increment each Array element by 1 position. Next you will need to call the method:
addBefore(myNums);//You can add the int x parameter and pass that as an arg if you want here
Next we can use the ArrayList.toArray() method in order to covert the ArrayList to an Integer Array. Here is an example below:
Integer[] integerHolder = new Integer[myNums.size()];
Integer[] numsArray = (Integer[])myNums.toArray(integerHolder);
System.out.println(Arrays.toString(numsArray));
First we create an ArrayHolder that will be the same size as your ArrayList, and then we create the Array that will store the elements of the ArrayList. We cast the myNums.toArray() to an Integer Array. The results will be as follows. The number 1 will be at index 0 and the rest of your elements will have incremented by 1 index:
[1, 2, 3, 4, 5]
You could do the entire process within the addBefore() method by converting the Array to an ArrayList within the method and adding (int x) to the 0 index of the ArrayList before converting it back into an Array. Since an ArrayList can only take a wrapper class object you'll simply need to convert the int primitive Array into the type Integer for this to work, but it simplifies your addBefore() method.

java arrays reverse not understanding the logic

I was trying to use this code I made to reverse a array. I don't understand why I was getting [I#7a84639c as my output in my console.
And for some reason why doesn't this method actually save my reversed array into the array? If i add a print at the bottom of x[i]=c[i]; it shows the array reversed but when i add a call for example karn[0] it shows that my array isn't actually reversed. I want to solve this by staying true to the code i made.
import java.util.Arrays;
public class HelloWorld {
public static void main(String[] args) {
int[]karn={1,2,3};
rev(karn);
System.out.println(karn.toString());
}
public static void rev(int[]x){
int[]c=new int[x.length];
for(int i=x.length-1;i>-1;i--){
c[i]=x[i];
x[i]=c[i];
}
}
}
in your rev method you are using a local variable for c. So this value will not be transferred over to your main method. You must return your array and assign the value to your old array:
public static int[] rev(int[]x){
//Creates new array this array is different from karn and local to the method.
//nothing outside of this method can see this array.
int[]c=new int[x.length];
for(int i = 0; i < c.length; i++){
//Here is where we are swapping the values by placing the first
//value at the last spot of the array and so on
c[c.length - i - 1] = x[i];
}
//we must return the new array we made and assign it to karn so our
//changes will be saved and seen outside of the method
return c;
}
In main method you must assign the changes of the rev method to karn. You can assign the value and display it like so:
karn = rev(karn);
//for each loop
for(int i : karn)
System.out.println(i);
//traditional for loop
for(int i = 0; i < karn.length; i++)
System.out.println(karn[i]);
Arrays do not have a default toString() method. That is why you are seeing the values of the array as you would like. You need to iterate through the array to display them to the console.
Your initial approach looked almost correct, you can do this in-place or through a copy. I posted a comment showing a copy, so I thought I might expand on in-place. I would start with a simple swap method, like
private static void swap(int[] x, int i, int j) {
if (i != j) {
int t = x[i];
x[i] = x[j];
x[j] = t;
}
}
Then you only need to iterate the first half of the array, swapping each element with the same index (but from the other half). Like,
public static void rev(int[] x) {
for (int i = 0; i < x.length / 2; i++) {
swap(x, i, x.length - i - 1);
}
}
Then you might call it like
public static void main(String[] args) throws IOException {
int[] karn = { 1, 2, 3 };
rev(karn);
System.out.println(Arrays.toString(karn));
}
for an output of
[3, 2, 1]

Why is a negative index value taken while inserting a new element into an java array?

I was trying out a java code to insert a new element into an array, I understand most of the program except for a line of code: "int newindex = -index-1;". Why does a negative sign used in front of the index?
Here is the full program:
public class ArrayManipulation2 {
public static void main(String[] args) {
int[] array = {6,3,5,2,-9,-5,-1,0};
Arrays.sort(array);
printArray(array);
int index= Arrays.binarySearch(array, 1);
int newindex = -index-1;
array = insertElement(array, 1, newindex);
printArray(array);
}
public static void printArray(int[] array){
for(int i=0; i<array.length; i++){
if(i!=0){
System.out.print(", ");
}
System.out.print(array[i]);
}
System.out.println();
}
public static int[] insertElement(int[] orginal, int element, int index){
int length = orginal.length;
int[] destination = new int[length+1];
System.arraycopy(orginal, 0, destination, 0, index);
destination[index]=element;
System.arraycopy(orginal, index, destination, index+1, length-index);
return destination;
}
}
I need to know why the new index is specified as "-index-1"?.
Arrays.binarySearch() returns a negative value if the item isn't already in the array, so that it can distinguish between where the item is if it is there and where it should be if it isn't there.
The code isn't correct without catering for the case where the result is positive.
Background:
The method Arrays.binarySearch() returns
the index of the search key, if it is contained in the array; otherwise, (-(insertion point) – 1). The insertion point is defined as the point at which the key would be inserted into the array: the index of the first element greater than the key, or a.length if all elements in the array are less than the specified key. Note that this guarantees that the return value will be >= 0 if and only if the key is found.
So, this API suggested be used in a sorted array, otherwise it could return unexpected return value
Then ,let me clarify the code :
If can not find the element, the method will return value "(-(insertion point) – 1)" , then get its "opposite number",so the value could be insertion+1, and then minus 1, we can get its right insert position

insert element into Array index out of bounds java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 6 years ago.
I have made an ADT called NumList, and have implemented it in a class NumArrayList
of the methods implemented, there is an insert(int i, double value) where value is inserted into array[i].
int numItems is a counter keeping track of my array's elements.
public void insert(int i, double value)
{
if (numItems >= items.length)
{
double[] tempItems = new double [items.length * 2];
for(int j =0 ; j < items.length; j++ )
{
tempItems[j] = items[j];
}
tempItems[items.length] = value;
items = tempItems;
}
else
{
if (i > numItems)
{
items[numItems] = value;
}
else
{
for (int k = i; k < numItems; k++)
{
items[k+1] = items[k];
}
items[i] = value;
}
}
numItems++;
}
is my method, looking simple enough.
public static void main (String[] args)
{
NumArrayList test;
test = new NumArrayList();
//System.out.println("this is how many initial items the initialized array has.");
//System.out.println(test.items);
test.insert(1, 0.1);
System.out.println("have tried to insert value 0.1 # position 1, that is the second element in array.");
test.print();
is my test code area, built into the same class.
I'm receiving an error where the compiler claims I have an ArrayIndexOutOfBoundsException at line 47, or at
tempItems[items.length] = value;
I believe it's trying to tell me that my initialization of items is wrong,
private double[] items;
private int numItems;
public NumArrayList()
{
items = new double[0];
numItems = 0;
}
but the initialization has already been approved by a much better programmer than I, and these errors are leading me nowhere. Perhaps a nudge as to which part of the program I should look into?
Your initialization is certainly wrong. What is a reasonable default size? For ArrayList the answer is 10. You can make it whatever you like, but not zero! If you double the length of an array with size 0, the new array still has length 0.
int capacity; //stores the size of the array (items available)
int numItems; //stores how many items are actually stored in the array.
public NumArrayList() {
items = new double[10];
numItems = 0;
capacity = 10;
}
You have to remember that array always starts with index 0 and not 1. So if your array size is 10, the maximum index is 9 and not 10.
tempItems[0] = first element;
tempItems[1] = second element;
etc etc
Assuming you have 10 elements, your tenth element will be in tempItems[9]. Trying to access tempItems[10] will throw the exception you're seeing. Basically if you're looking for the last index, you want to do:
tempItems[items.length-1] = value;
EDIT: Forget this. You're doubling your array index on initialization. Refer to Thorn's post above.
change this
tempItems[items.length] = value;
to
tempItems[items.length-1] = value;
array index starts with 0, if your array is of length 5, your last index would be 4
Once you allocate places to an array , lets say items = new double[0]; then you cannot change the size of the array. If the array is initialised to 0, that means you have a useless array. Anything you add to it, it will throw Array index out of bounds exception.
The way to go is by using Collections and specifically the List interface.
List myList = new List(); //Create an empty list
myList.add(item); //adds item to List
There are also other implementations of List, like ArrayList, LinkedList etc... that can fit better your needs .

Categories