How to reverse a Java array [duplicate] - java

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have this extremely simple program to reverse an array of integers but every time I try to run it, it just ignores the second loop where the reverse should happen and passes it or there maybe some trouble in it.
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int[] arr = new int[10];
for (int i = 0; i < arr.length; i++) {
System.out.println("[%" + i + "]=");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
}

it does not ignore the second loop, it simply should be
for (int i = 0; i < arr.length/2; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
beacuse if you iterate from 0 to arr.length it will reverse Your array twice which in the end gives You back original array,

Just change arr.length to arr.length/2. Now you are reversing it twice.

You should browse your array until his half for not reversing twice ( -- => +).
Always try to use the array size to the browse.
for (int i = 0; i < arr.length; i++)
and not
for (int i = 0; i < 10; i++)
It's more general and correct. You can add a variable to save the array size.
So your code will:
package chapter_1;
import java.util.*;
public class Reverse_array {
public static void main(String[] args) {
Scanner keybd = new Scanner(System.in);
int arrayLenght = 10;
int[] arr = new int[arrayLenght];
for (int i = 0; i < arrayLenght; i++) {
System.out.print("%[" + i + "]= ");
arr[i] = keybd.nextInt();
}
for (int i = 0; i < arrayLenght / 2; i++) {
int temp = arr[i];
arr[i] = arr[arrayLenght - 1 - i];
arr[arrayLenght - 1 - i] = temp;
}
for (int i = 0; i < arrayLenght; i++) {
System.out.println(arr[i]);
}
}
}

I see that others gave you the solution as i'm writing.
Let me give you some suggestions:
-whatever you are trying, magane to keep the developing loop (error, modification, trial and again from start) as short as possible.
-insert data by hand rarely is a good option
so, in this case: better to avoid the first loop and put something like:int [] arr ={5,6,7,8,8,1,8,9,1,9};
-when in doubt fill the code with print so you can follow what the algorithm is doing,the next step will be learn to use the debugger but the first is the print instructions
-if you want to learn, try hard enough (it depends by you) before ask other's people help

Here is the problem
for (int i = 0; i < arr.length; i++) {
int temp = arr[i];
arr[i] = arr[10 - 1 - i];
arr[10 - 1 - i] = temp;
}
You make twice array elements swap
Instead, use
for (int i = 0; i < arr.length / 2; i++) {
int temp = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = temp;
}

Related

Java : Selection Sort Logic

I am printing Sorted Array elements using Selection Sort. But I am getting my input array elements as output in same sequence without sorting.
public class SelectionSort {
public static void main(String[] args) {
int[] arr= {1,9,3,0,7};
int n=arr.length;
for(int i=0; i<n-1; i++)
{
int minimumIndex = i;
for(int j=i; j<n; j++)
{
if(arr[j]<arr[minimumIndex])
{
minimumIndex=j;
}
}
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
}
for(int e: arr)
{
System.out.print(e+" ");
}
}
}
Expected o/p : 0 1 3 7 9
Actual o/p: 1 9 3 0 7
In Your method code, the actual problem is swapping elements,
the Sequence needs to be like this as below,
int temp=arr[minimumIndex];
arr[minimumIndex]=arr[i];
arr[i] =temp;
instead of
int temp=arr[i];
arr[i]=arr[minimumIndex];
arr[i]=temp;
There are two issues I see. One is the way you are swapping the items. You need to replace the item where you found the minimum index. Also, your J index should start one after your I index. You can assume that the one before it is the smallest as you are looping through. I have changed a few pieces of the code and tested it and it works fine for me.
for (int i = 0; i < arr.length - 1; i++)
{
int minimumIndex = i;
for (int j = i + 1; j < arr.length; j++)
{
if (arr[j] < arr[minimumIndex])
{
minimumIndex = j;
}
}
int temp = arr[i];
arr[i] = arr[minimumIndex];
arr[minimumIndex] = temp;
}

Changing sorting algorithm java

starting Java coder here. I was wondering how to change my code so it would sort array by always swapping the biggest value to first. Sample output should be:
[3, 1, 2, 0] [3, 2, 1, 0].
public class Sorting {
static void biggest(int[] arr, int start, int end) {
for (start = 0; start < arr.length; start++) {
for (end = start + 1; end < arr.length; end++) {
if (arr[start] < arr[end]) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
System.out.println(Arrays.toString(arr));
}
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3};
int temp = 0;
for (int i = 0; i < 4; ++i) {
biggest(arr, temp, 4 - 1);
for (int j = 0; j < 4; ++j) {
}
++temp;
}
}
Thanks in advance,
- Em
If you just want the sort to be successful, I suggest taking advantage of Java's built in sort method then reversing the list as suggested here:
Arrays.sort(arr);
ArrayUtils.reverse(arr);
But it sounds like the spirit of your question is to modify your code for this purpose. Here's the solution I came up with:
import java.util.Arrays;
public class Sorting {
static void biggest(int[] arr) {
for (int i = 0; i < arr.length; i++) {
System.out.println(Arrays.toString(arr));
int max, maxAt = i;
for (int j = i; j < arr.length; j++) {
maxAt = arr[j] > arr[maxAt] ? j : maxAt;
}
max = arr[maxAt];
if (arr[i] < max) {
arr[maxAt] = arr[i];
arr[i] = max;
}
}
}
public static void main(String[] args) {
int[] arr = {0, 1, 2, 3};
biggest(arr);
System.out.println(Arrays.toString(arr));
}
}
First off, you had a lot of extra code that you didn't need. It's a bad idea to have a loop in your main. That should be handled by the helper function. You also had a lot of redundant declarations (like start and end). You were on the right track with your helper function, but because of your main loop your time complexity was 0(n²). Eliminating that allows mine to be O(logn). Complexity aside, the key difference in terms of logic is here in your internal loop:
for (end = start + 1; end < arr.length; end++) {
if (arr[start] < arr[end]) {
int temp = arr[end];
arr[end] = arr[start];
arr[start] = temp;
In this loop you're switching the array entry with the first one you find that's bigger. This will result in unwanted early switches (like 1 & 2). Here is my solution:
for (int j = i; j < arr.length; j++) {
maxAt = arr[j] > arr[maxAt] ? j : maxAt;
}
max = arr[maxAt];
if (arr[i] < max) {
arr[maxAt] = arr[i];
arr[i] = max;
}
The key difference is that I search for the maximum value entry following the one we're swapping. That way as we proceed through the array we will always bring forward the next biggest.
Best of luck learning Java I hope this helps!

Algorithm for sorting an array in java

I want to sort an array of int from the smallest value to the greatest one. I have created the next algorithm but the problem is that the new array does't receive the right values from the if statement. I am going put my code bellow.
public static void main(String[] args) {
int[] arr = {33,44,22,11,22,11};
int[] arrSort = new int[6];
int temp=0;
for (int i = 0; i < arrSort.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arrSort[i] = temp;
}
else {
arrSort[i] = arr[i];
}
}
System.out.println(Arrays.toString(arrSort));
}
If i run the code I get the next values: [33, 22, 11, 22, 11, 0];
I just want to figure out what part of the algorithm was thought wrong. Thank you in advance.
You need to apply 2 loops.
1st loop is to access 1st arr element.
2nd loop is to access next(1st + 1)th element.
After comparing 1st element with other swap it accordingly.
public static void main(String []args)
{
int[] arr = {33,44,22,11,22,11};
int len=arr.length;
int temp=0,i,j;
for (i = 0; i < len; i++)
{
for (j = i+1; j < len; j++)
{
if (arr[i] > arr[j])
{
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(i=0; i<arr.length; i++)
{
System.out.println(arr[i]);
}
}
when it is the case of array Loops are very handy to use.
int[] yourArary = new int[10];
ArrayList<Integer> intArray = new ArrayList<>();
for( int value : yourArary ){
intArray.add( value );
}
Arrays.sort(intArray);
System.out.println(Arrays.toString(yourArary));
// you can short like this in reverse order
for (int i = yourArary.length - 1; i >= 0; i--)
System.out.print(yourArary[i] + " ");
System.out.println();
You cannot do it with just one loop. Sorting is a more complex than that. For bubble sort or selection sort it's like O(n^2). There are better algorithms that like quick sort or merge sort that have better results and aim for O(n log N) complexity. But anyway you can do it like that for example for a simple bubble sort implementation:
int[] arr = {33,44,22,11,22,11};
for (int i = 0; i < arrSort.length - 1; i++) {
for(int j=i;j<arrSort.length; j++) {
if (arr[i] > arr[j]) {
temp = arr[j];
arr[j] = arr[i];
arr[i]=temp;
}
}
System.out.println(Arrays.toString(arr));
Don't know if this will help you, but why sort it by yourself, if Java can do the Job:
int[] unsortedArray = { 33, 44, 22, 11, 22, 11 };
ArrayList<Integer> intArray = new ArrayList<>();
for( int value : unsortedArray )
{
intArray.add( value );
}
Collections.sort( intArray );
System.out.println( intArray );
If you use the helper variable temp to move positions, you don't need a second array, just put it back into arr[i]. Second, one run is not enough, you will need to run this, until there are no position changes needed. So it would look like this:
public static void main(String[] args) {
//source Array
int[] arr = {33,44,22,11,22,11};
int temp=0;
//marker, that positions were switched
boolean sthChanged = false;
do
{
//in each run assume that nothing is left to change
sthChanged = false;
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
//we found an instance, where the earlier position holds a higher int than the latter
//save the latter value in the temp variable
temp = arr[i + 1];
//move the former value to the latter position
arr[i + 1] = arr[i];
//fill the former position with the value from the temp variable
arr[i] = temp;
//set the marker to true, as there might be other changes to be done
sthChanged = true;
}
}
}
while (sthChanged); //stop only, if we didn't find sth to be changed in the last run
System.out.println(Arrays.toString(arr));
}
Best regards
First of all, u shud not use two arrays in your algorithm, as its just a waste of memory and unecessary array access overhead. If u need to retain the original array copy it over, and send the copied array to the sort method.
Secondly, for the method adopted here (bubble sort), you are iterating the array and finding the largest element and shifting it to the end.
U need to repeat this process, for each subarray of length-1, length-2 ... 1.
So the time complexity of this approach would be O(n^2). There are better algorithms, like MergeSort, QuickSort which can do the sort in the theoretical O(n log(n)) time.
See below the correctin required for your code :
public static void main(String[] args) {
int[] arr = {33,44,22,11,22,11};
//int[] arrSort = new int[6];
int temp=0;
for(int j = 0; j < arr.length; j++) {
for (int i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) {
temp = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
System.out.println(Arrays.toString(arr));
}

After counting sort the result array has one more element (0) than the original one

So I have a problem, this method is supposed to sort an array of integers by using counting sort. The problem is that the resulting array has one extra element, zero. If the original array had a zero element (or several) it's fine, but if the original array didn't have any zero elements the result starts from zero anyway.
e.g. int input[] = { 2, 1, 4 }; result -> Sorted Array : [0, 1, 2, 4]
Why would this be happening?
public class CauntingSort {
public static int max(int[] A)
{
int maxValue = A[0];
for(int i = 0; i < A.length; i++)
if(maxValue < A[i])
maxValue = A[i];
return maxValue;
}
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length + 1];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
Result[x] = A[i];
x--;
Count[A[i]] = x;
}
return Result;
}
}
You are using int[] Result = new int[A.length + 1]; which makes the array one position larger. But if you avoid it, you'll have an IndexOutOfBounds exception because you're supposed to do x-- before using x to access the array, so your code should change to something like:
public static int[] createCountersArray(int[] A)
{
int maxValue = max(A) + 1;
int[] Result = new int[A.length];
int[] Count = new int[maxValue];
for (int i = 0; i < A.length; i++) {
int x = Count[A[i]];
x++;
Count[A[i]] = x;
}
for (int i = 1; i < Count.length; i++) {
Count[i] = Count[i] + Count[i - 1];
}
for (int i = A.length -1; i >= 0; i--) {
int x = Count[A[i]];
x--;
Result[x] = A[i];
Count[A[i]] = x;
}
return Result;
}
Here you go: tio.run
int maxValue = max(A) + 1;
Returns the highest value of A + 1, so your new array with new int[maxValue] will be of size = 5;
The array Result is of the lenght A.lenght + 1, that is 4 + 1 = 5;
The first 0 is a predefinied value of int if it is a ? extends Object it would be null.
The leading 0 in your result is the initial value assigned to that element when the array is instantiated. That initial value is never modified because your loop that fills the result writes only to elements that correspond to a positive number of cumulative counts.
For example, consider sorting a one-element array. The Count for that element will be 1, so you will write the element's value at index 1 of the result array, leaving index 0 untouched.
Basically, then, this is an off-by-one error. You could fix it by changing
Result[x] = A[i];
to
Result[x - 1] = A[i];
HOWEVER, part of the problem here is that the buggy part of the routine is difficult to follow or analyze (for a human). No doubt it is comparatively efficient; nevertheless, fast, broken code is not better than slow, working code. Here's an alternative that is easier to reason about:
int nextResult = 0;
for (int i = 0; i < Count.length; i++) {
for (int j = 0; j < Count[i]; j++) {
Result[nextResult] = i;
nextResult++;
}
}
Of course, you'll also want to avoid declaring the Result array larger than array A.

Array in the reverse order [duplicate]

This question already has answers here:
How do I reverse an int array in Java?
(47 answers)
Closed 8 years ago.
I have an array of n elements and these methods:
last() return the last int of the array
first() return the first int of the array
size() return the length of the array
replaceFirst(num) that add the int at the beginning and returns its position
remove(pos) that delete the int at the pos
I have to create a new method that gives me the array at the reverse order.
I need to use those method. Now, I can't understand why my method doesn't work.
so
for (int i = 1; i
The remove will remove the element at the position i, and return the number that it is in that position, and then with replaceFirst will move the number (returned by remove) of the array.
I made a try with a simple array with {2,4,6,8,10,12}
My output is: 12 12 12 8 6 10
so if I have an array with 1,2,3,4,5
for i = 1; I'm gonna have : 2,1,3,4,5
for i=2 >3,2,1,4,5
etc
But it doesn't seem to work.
Well, I'll give you hints. There are multiple ways to reverse an array.
The simplest and the most obvious way would be to loop through the array in the reverse order and assign the values to another array in the right order.
The previous method would require you to use an extra array, and if you do not want to do that, you could have two indices in a for loop, one from the first and next from the last and start swapping the values at those indices.
Your method also works, but since you insert the values into the front of the array, its going to be a bit more complex.
There is also a Collections.reverse method in the Collections class to reverse arrays of objects. You can read about it in this post
Here is an code that was put up on Stackoverflow by #unholysampler. You might want to start there: Java array order reversing
public static void reverse(int[] a)
{
int l = a.length;
for (int j = 0; j < l / 2; j++)
{
int temp = a[j]
a[j] = a[l - j - 1];
a[l - j - 1] = temp;
}
}
int[] reverse(int[] a) {
int len = a.length;
int[] result = new int[len];
for (int i = len; i > 0 ; i--)
result[len-i] = a[i-1];
return result;
}
for(int i = array.length; i >= 0; i--){
System.out.printf("%d\n",array[i]);
}
Try this.
If it is a Java array and not a complex type, the easiest and safest way is to use a library, e.g. Apache commons: ArrayUtils.reverse(array);
In Java for a random Array:
public static void reverse(){
int[] a = new int[4];
a[0] = 3;
a[1] = 2;
a[2] = 5;
a[3] = 1;
LinkedList<Integer> b = new LinkedList<Integer>();
for(int i = a.length-1; i >= 0; i--){
b.add(a[i]);
}
for(int i=0; i<b.size(); i++){
a[i] = b.get(i);
System.out.print(a[i] + ",");
}
}
Hope this helps.
Reversing an array is a relatively simple process. Let's start with thinking how you print an array normally.
int[] numbers = {1,2,3,4,5,6};
for(int x = 0; x < numbers.length; x++)
{
System.out.println(numbers[x]);
}
What does this do? Well it increments x while it is less than numbers.length, so what is actually happening is..
First run : X = 0
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[0]);
// Which resolves to..
System.out.println(1);
Second Run : X = 1
System.out.println(numbers[x]);
// Which is equivalent to..
System.out.println(numbers[1]);
// Which resolves to..
System.out.println(2);
What you need to do is start with numbers.length - 1, and go back down to 0. To do this, you need to restructure your for loop, to match the following pseudocode..
for(x := numbers.length to 0) {
print numbers[x]
}
Now you've worked out how to print, it's time to move onto reversing the array. Using your for loop, you can cycle through each value in the array from start to finish. You'll also be needing a new array.
int[] revNumbers = new int[numbers.length];
for(int x = numbers.length - 1 to 0) {
revNumbers[(numbers.length - 1) - x] = numbers[x];
}
int[] noArray = {1,2,3,4,5,6};
int lenght = noArray.length - 1;
for(int x = lenght ; x >= 0; x--)
{
System.out.println(noArray[x]);
}
}
int[] numbers = {1,2,3,4,5};
int[] ReverseNumbers = new int[numbers.Length];
for(int a=0; a<numbers.Length; a++)
{
ReverseNumbers[a] = numbers.Length - a;
}
for(int a=0; a<ReverseNumbers.Length; a++)
Console.Write(" " + ReverseNumbers[a]);
int[] numbers = { 1, 2, 3, 4, 5, 6 };
reverse(numbers, 1); >2,1,3,4,5
reverse(numbers, 2); >3,2,1,4,5
public int[] reverse(int[] numbers, int value) {
int index = 0;
for (int i = 0; i < numbers.length; i++) {
int j = numbers[i];
if (j == value) {
index = i;
break;
}
}
int i = 0;
int[] result = new int[numbers.length];
int forIndex = index + 1;
for (int x = index + 2; x > 0; x--) {
result[i] = numbers[forIndex--];
++i;
}
for (int x = index + 2; x < numbers.length; x++) {
result[i] = numbers[x];
++i;
}
return result;
}

Categories

Resources