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];
}
}
}
Related
I am having an issue with a fill-in-the-code digital textbook problem. All the code is permanent and cannot be changed, so the problem can only be solved by using the area that states //Write code here.
The problem asks to implement the removeOdd method.
import java.util.Arrays;
public class RemoveTester
{
public static int removeOdd(int[] values, int size)
{
//Write code here
}
public static void main(String[] args)
{
int[] a = { 22, 98, 95, 46, 31, 53, 82, 24, 11, 19 };
int sizeBefore = 8;
int sizeAfter = removeOdd(a, sizeBefore);
System.out.print("a: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ 22 98 46 82 24 ]");
int[] b = { 23, 97, 95, 45, 31, 53, 81, 24, 11, 19 };
sizeBefore = 7;
sizeAfter = removeOdd(b, sizeBefore);
System.out.print("b: [ ");
for (int i = 0; i < sizeAfter; i++)
{
System.out.print(b[i] + " ");
}
System.out.println("]");
System.out.println("Expected: [ ]");
}
}
The way I tried to implement removeOdd is by doing:
int evenCount = 0;
for(int i = 0; i<size; i++){
if(values[i]%2==0){
evenCount++;
}
}
int[] newValues = new int[evenCount];
int newCount =0;
for(int i = 0; i<evenCount; i++){
if(values[i]%2==0){
newValues[newCount] = values[i];
newCount++;
}
}
values = newValues;
return evenCount;
When the program is compiled and ran, main prints the beginning of the original a or b arrays instead of only the even elements in a or b. I cannot find a way to alter the original arrays within the method removeOdd into the new arrays with only their even elements. I can't think of any other way to do this either. Any help would be greatly appreciated!
The other answers give a good description of what the problem is with your overall approach...that is, why your results don't make it back to the calling method.
If your code were otherwise correct, you could use it as is and just copy the result back into the original array at the end. As it is, you had one flaw in your logic. So if you fix that flaw, and then do the copy at the end, you should get the correct result:
public static int removeOdd(int[] values, int size)
{
int evenCount = 0;
for(int i = 0; i<size; i++){
if(values[i]%2==0){
evenCount++;
}
}
int[] newValues = new int[evenCount];
int newCount =0;
for(int i = 0; i<size; i++) { // <- Need to iterate over the entire input array
if(values[i]%2==0){
newValues[newCount] = values[i];
newCount++;
}
}
for (int i = 0 ; i < evenCount ; i++) // <- now copy your result to the original array
values[i] = newValues[i];
return evenCount;
}
Rather than creating an extra array to temporarily hold the even values, you can use the same logic to copy into the original array directly:
public static int removeOdd(int[] values, int size)
{
int newCount =0;
for(int i = 0; i<size; i++) {
if(values[i]%2==0){
values[newCount] = values[i];
newCount++;
}
}
return newCount;
}
Because Java is pass by value and not pass by reference, setting the value of the values argument will not change the value of the a variable.
What you have to do is remove all the odd elements from the array and shift the remaining even elements to the left so that the actual resultant form of a looks like this:
{22, 98, 46, 82, 24, 0, 0, 0, 0, 0}
As #Geoff pointed out Java is pass by value, which means when you pass your array as an argument, what you get inside the method is a reference to the array object which is different from the original reference int[] a you have inside your main method (the caller). Therefore, when you do values = newValues; you are pointing that new reference which used to point to the same object as int[] a to the array object newValues points to, thereby not updating the original array a but actually losing any reference to it.
This question already has answers here:
Find first element by predicate
(8 answers)
Closed 5 years ago.
I have tried with the below code. Please help me to get the output.
I want simple code that I can understand.
Suppose that number is 40:
public class PositionofElementinArray {
public static void main(String args[]) {
int arr[] = {10, 20, 30, 40, 50};
int value = 40;
for(int i=0; i < arr.length; i++)
if(arr[i]==value){
System.out.print(arr[i]);
}
else{
System.out.print("no element found");
}
}
}
if(arr[i]==value) here you are checking the value.
And i is the index/position
This code will print the value and its position.according to your example value is 40 position is 3.
class Test
{
public static void main (String[] args)
{
int arr[] = {10, 20, 30, 40, 50};
int value = 40;
for(int i=0; i < arr.length; i++)
{
if(arr[i]==value){
System.out.print("value is"+arr[i]+" "position is"+i);
}
}
}
}
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));
sorry to repost this question again but I really need the answer.
What I need is to get the answer to the bubble list (on one class) to appear on another class, as shown below:
public class BubbleSort4
{
public static void main(String[] args) {
int intArray[] = new int[]{5,90,35,45,150,3};
System.out.println("Array Before Bubble Sort");
for(int i=0; i < intArray.length; i++)
{
System.out.print(intArray[i] + " ");
}
bubbleSort(intArray);
System.out.println("");
System.out.println("Array After Bubble Sort");
for(int i=0; i < intArray.length; i++)
{
System.out.print(intArray[i] + " ");
}
}
private static void bubbleSort(int[] intArray)
{
int n = intArray.length;
int temp = 0;
for(int i=0; i < n; i++)
{
for(int j=1; j < (n-i); j++)
{
if(intArray[j-1] > intArray[j])
{
temp = intArray[j-1];
intArray[j-1] = intArray[j];
intArray[j] = temp;
}
}
}
}
}
And get the answer to the above coding to appear on OddArr3:
System.out.println ("Bubble Sort : " +
bubbleSort.sortBubble(intArray));
System.out.println ("Bubble Sort : " + bubbleSort.sortBubble(intArray)); does not seem to work.
Below is the full coding to OddArr3
import java.util.ArrayList;
import java.util.List;
import java.util.*;
public class OddArrSe3:
{
public static void main(final String[] args)
{
int[] array_sort = {10,41,21,24,34,15,40,12,32,23,13,25,30,31,22,33,14,35,20,11};
ArrayList<Integer> OddArr = new ArrayList<Integer>();
ArrayList<Integer> EvenArr = new ArrayList<Integer>();
for (int i : array_sort)
{
if ((i & 1) == 1)
{
OddArr.add(i);
}
else
{
EvenArr.add(i);
}
}
Collections.sort(OddArr);
Collections.sort(EvenArr);
System.out.println("Odd:" + OddArr);
System.out.println("Even:" + EvenArr);
int OddArr2[] = {11, 13, 15, 21, 23, 25, 31, 33, 35, 41};
int toSearch = 31;
int EvenArr2[] = {10, 12, 14, 20, 22, 24, 30, 32, 34, 40};
int toSearch2 = 32;
LinearSearch4 linearSearch = new LinearSearch4();
BinarySearch4 binarySearch = new BinarySearch4();
Bubblesort4 bubblesSort = new BubbleSort4();
System.out.println("Linear Search Index : "
+ linearSearch.searchLinear(OddArr2, toSearch));
System.out.println("Binary Search Index : "
+ binarySearch.searchBinary(EvenArr2, toSearch2));
**System.out.println ("Bubble Sort : " + bubbleSort.sortBubble(intArray));**
}
}
To answer your question. Your method should be public, not private. Then you can access it.
I have also two remarks:
First of all, why do you have two main methods? In small prorgrams you usually need one just to start the program.
In addition try to NOT use names for classes/methods like OddArr2/
OddArrSe3. They make code less understandable.
1) please remove the colon after the class name 'OddArrSe3'
2) As Marcin Szymczak pointed out, two main methods are not required.
3) change the signature of method bubbleSort to public int[] bubbleSort(int[] intArray) and return intArray after sorting. (private methods are not accessible outside the class in which they are declared)
You're calling a static method from an instance. It should be BubbleSort4.bubbleSort(...).
Make following changes and re try
Remove : from OddArrSe3:
Make your BubbleSort4.bubbleSort() method public
call BubbleSort4.bubbleSort(array_sort); to short your array
BubbleSort4.bubbleSort() method is void it will give compilation error if you call it as follows:
System.out.println ("Bubble Sort : "+BubbleSort4.bubbleSort(array_sort));
Either change return type of your method as public int[] bubbleSort() and return sorted array or use a for loop to traverse your array and print the sorted numbers
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...