Java: Insertion Sort Algorithm [duplicate] - java

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 7 years ago.
Hello fellow Stackoverflowers,
How do I print out the numbersArray so that I can see the numbers?
When I sysout the numbersArray, it shows me:
[I#677327b6
[I#677327b6
Thank you for your time and help!
package AlgoExercises;
public class InsertionSort {
static int[] numbersArray = { 5, 2, 4, 6, 1, 3 };
static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
// a and b are copies of the original values.
// The changes we made here won't be visible to the caller.
}
static void insertionSort(int[] numbersArray) {
for (int i = 1; i < numbersArray.length; i++) {
int j = i;
while ((j > 0) && (numbersArray[j] < numbersArray[j - 1])) {
swap(numbersArray[j], numbersArray[j - 1]);
j = j - 1;
System.out.println(numbersArray);
}
}
}
public static void main(String args[]) {
insertionSort(numbersArray);
}
}

System.out.println(numbersArray); You are printing an array instead of values. you should print the value by numbersArray[i]

For printing out arrays use java.lang.Arrays.toString() method:
System.out.println(Arrays.toString(numbersArray));

Related

array method issue in output [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 4 years ago.
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
list = newList;
}
}
how come the method does not apply and still get 1 2 3 4 5?
thank you !
This is happening because Java is pass by value. This means that when you pass an argument into a method you are passing the reference to it, not the argument itself. The changes that you make inside the method are resolved but in this case you don't return the modified argument. Try this simple experiment to see what I mean:
public static void main(String[] args) {
int x = 0;
foo(x);
System.out.println(x);
}
public static void foo(int x) {
x = 4;
}
This program will print 0 because the changes are essentially discarded. To return the copied reference try this:
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++) {
newList[i] = list[list.length - 1 - i];
}
return newList;
}
And in your main:
oldList = reverse(oldList);
A much more in depth answer:
Is Java "pass-by-reference" or "pass-by-value"?
There are couple of issues. You can fix it with below two Options:
Option 1:
1) Make a new copy of original array and use it as reference array to reverse
2) In reverse function, update values of array that has been passed in parameter and reverse it using reference array
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static void reverse(int[] list) {
// create a copy of initial array to use it to reverse
int[] newList = Arrays.copyOf(list,list.length);
for (int i = 0; i < list.length; i++)
// update original array and reverse it. Calling method still have reference to this array
list[i] = newList[list.length - 1 - i];
}
}
Console Output:
PS: Here the idea is to ensure the reference of array remains the same. You can do it using another array as reference array or using another local variable and swapping two values inside array or doing XOR between i and n-i-1 variable. There are n number of ways out of which 1 has been shared above.
Option 2:
1) No need to copy the reference of the old array to new array in reverse method
2) Return the new array reference back to the calling method
3) For above point you will also have to change the return type of reverse function
4) Save the new reference of array in a variable in the main method and then print from the same.
Please find my comments below:
public class Test {
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
//save the return list to a variable
int[] newList= reverse(oldList);
for (int i = 0; i < newList.length; i++)
//print the data from new list
System.out.print(newList[i] + " ");
}
// change the return type
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
//remove this line as there is no point of copying old array back to new array
// list = newList;
//retrun newlist reference to the calling method
return newList;
}
}
Console Output:
This is happening because you are altering the new area, and the statement list = newList; does not affect the original list because java is pass by value and you only overwrite the pointer in the reverse function.
Instead you should return the new array and overwrite the old one like:
public class HelloWorld
{
public static void main(String[] args) {
int[] oldList = {1, 2, 3, 4, 5};
oldList = reverse(oldList);
for (int i = 0; i < oldList.length; i++)
System.out.print(oldList[i] + " ");
}
public static int[] reverse(int[] list) {
int[] newList = new int[list.length];
for (int i = 0; i < list.length; i++)
newList[i] = list[list.length - 1 - i];
return newList;
}
}
Java is always pass-by-value. What does this mean for object- and array-references? In Java, we handle objects only through references. References live on the stack, the actual objects live on the heap. References store the address where the actual object resides.
If you pass an object to a method, the reference-value (i.e. the address where the object resides) is passed as parameter. For some method foo(Object o) this means: if you re-assign o in foo's body (e.g. through o = new Object();, this change will not be visible outside the method.
To fix you problem, you would either have to do the reversal in-place (i.e. on list directly) or return your newly created array. Here is an implementation of the in-place variant:
public static void reverse(final int[] values) {
final int length = values.length;
for (int i = 0; i < length / 2; ++i) {
final int j = length - i - 1;
swap(values, i, j);
}
}
public static void swap(final int[] values, final int i, final int j) {
int tmp = values[i];
values[i] = values[j];
values[j] = tmp;
}
For an implementation of the return-variant, look at one of the other answers since every other answer seems to implement a variant on this.
Some remarks on your code:
Giving an array-parameter the name list is confusing. A list is not the same as an array, the are different datastructures with differen properties.
You should never neglect the optional parentheses around one-line if-, else-, for-,... bodies. This can be the source of nasty bugs and is regarded as bad practice.
You should take a little bit more care wrt. your indentation. Keep in mind that your source code is a means of coummuncation. The more semantics you can transport through simple rules (like indentation), the easier it is to understand your source code.

Exception in creating array of Objects [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I am storing sum of all pairs of an array element to pairSum[] array.
For this I have created PairSum class which store two elements and their sum.
But I am getting null Pointer Exception on line pairSum[k].sum = v
I have created array as
PairSum[] pairSum = new PairSum[val];
What am I doing wrong?
public class test {
class PairSum{
int first;
int second;
int sum;
}
public static void findElements(int arr[], int n){
int val = (n*(n-1))/2;
PairSum[] pairSum = new PairSum[val];
int k=0;
for(int i=0;i<n-1;i++){
for (int j=i+1;j<n;j++){
int v = arr[i] + arr[j];
System.out.println("sum..." + v);
pairSum[k].sum = v;//NullPointerException here
System.out.println("valll.." + pairSum[k]);
pairSum[k].first = arr[i];
pairSum[k++].second = arr[j];
}
}
}
public static void main(String[] args) {
int arr[] = {10, 20, 30, 40, 1, 2};
int n = arr.length;
findElements (arr, n);
}
}
As of now, you have only created an array that can hold objects of type PairSum. You need to instantiate every PairSum object individually:
pairSum[k] = new PairSum();
Before accessing any PairSum in your pairSum array.

Java program which accepts Integer array as parameter and randomise its values [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I tried a program where I take an integer array and randomise values in it. but I am not able to understand why but am getting a crazy output which displays special characters and all. what's wrong with my question. Here is my code:
import java.util.Random;
public class Q2d {
public static void shuffle(int[] arr) {
int n = arr.length;
Random random = new Random();
random.nextInt();
for (int i = 0; i < n; i++) {
int change = i + random.nextInt(n - i);
int temp = arr[i];
arr[i] = arr[change];
arr[change] = temp;
}
}
public static void main(String args[]) {
int[] arr = { 1, 2, 3, 4, 5, 6 };
shuffle(arr);
System.out.println(arr);
}
}
You are attempting to print the array object. Arrays are objects too, but they don't override Object's toString() method, which is responsible for the "crazy output".
Use Arrays.toString():
System.out.println(Arrays.toString(arr));
I'm pretty sure you asked this question like 20 minutes ago and in it instead of
System.out.println(arr);
you had
for(int i:arr){
System.out.println(i);
}
which is correct...

How to print a histogram? [duplicate]

This question already has answers here:
What's the simplest way to print a Java array?
(37 answers)
Closed 9 years ago.
I'm trying to print a histogram, but am having trouble piecing it all together in main. I'm new to arrays, so if anyone can help with this, it'd be much appreciated. Here are my methods:
public static void main(String[] args) {
randomIntArray(5);
}
public static int randomInt(int low, int high){
int x= (int)(Math.random ()*high)+low;
return x;
}
public static int[] randomIntArray(int n){
int[] a = new int [n];
for (int i = 0;i<a.length;i++){
a[i]=randomInt (0,100);
}
System.out.println(printHist(a));
return a;
}
public static int[] printHist(int[]a){
int[] k = new int[11];
int i=0;
while (i<=10) {
int counter = 0;
int h=0;
while(h<a.length) {
if (a[h] == i) {
counter++;
h++;
}
h++;
}
k[i] = counter;
i++;
}
return k;
}
And here's what I get as output.
[I#fb53f6
Do I need to rethink the way I'm doing this, or is there a simple fix?
System.out.println(arrayObject) does not do what you think it does.
Try one of the solutions at this related question: What's the simplest way to print a Java array? - such as Arrays.toString(arrayObject)

Reverse order of single dimensional array in Java [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I reverse an int array in Java?
I need to reverse the order of the given numbers in the array without using a temp.
public class Reverse
{
public static void main (String[] args)
{
int[] num = { 12, 34, 50, 67, 88 }, cl, cl2;
for (i=0; i < a.length; i++)
{
cl = a[i];
cl2 = a[(a.length - 1 )-1];
System.out.println (cl1 + " " + cl2);
}
}
}
Since it only seems that you're printing the values out, you can iterate over your array backwards.
for(int i = a.length - 1; i >= 0; i--) {
// relevant code here
}
you can use Collections#reverse to inline a reverse sort of the integer array,
Collections.reverse(Arrays.asList(num));
The answers given are perfect. But i just added another answer in case if you want to store the reverse array into the original array without using any temp. use this.
public class Reverse
{
public static void main (String[] args)
{
int[] a = { 12, 34, 50, 67, 88 };
int i, j;
for (i = 0, j = a.length - 1; i < j; i++, j--)
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}

Categories