Efficient Swapping of Elements of an Array in Java

Efficient swapping of elements of an array in Java

Nope. You could have a function to make it more concise each place you use it, but in the end, the work done would be the same (plus the overhead of the function call, until/unless HotSpot moved it inline — to help it with that, make the function static final).

Swapping elements in array (Java)

Is there any predefined method for array in Java with which one can
directly swap two elements ?

Default Java API does not have any function to swap array elements. But you can swap elements of list with Collections.swap(list, index1, index2); and you can convert array to list and perform swap and then convert list to array.

If you don't want to perform such operation you can look into some third party library which can provide such function.

You can also create your own generic function.

For example,

public class Test {

@SuppressWarnings("unchecked")
public static <T> void swap(T[] arr, int index1, int index2) {
// Need to add null check and index checks
List<T> list = Arrays.asList(arr);
Collections.swap(list, index1, index2);
arr = (T[]) list.toArray();
}

public static void main(String[] args) {
Integer[] arr = { 1, 2, 3, 4, 5 };
swap(arr, 1, 2);
System.out.println(Arrays.asList(arr));
}

}

OUTPUT

[1, 3, 2, 4, 5]

NOTES :

  1. Above function will not work for primitive arrays
  2. SuppressWarnings is added to avoid uncheck casting warning

How to write a swap method that takes an array and two integers

static <T> void swap(T[] array, int a, int b){
T temp = array[a];
array[a] = array[b];
array[b] = temp;
}

Swapping element in an array

Try this:

for (int i = 1 ; i < n.length ; i++)
if (n[i] == 0 && n[i - 1] != 0) {
int tmp = n[i - 1];
n[i - 1] = n[i];
n[i] = tmp;
}

You were right in thinking that you would need a for loop with an if statement in its body. All we're doing here is looping through the array starting at element 1. We then check if the element we're currently on is 0 and the previous element is not 0: i.e. if (n[i] == 0 && n[i - 1] != 0). If this condition is true, we swap these two elements.

Which is more efficient for array lists: collections.swap() or using a temporary variable to swap?

I want to swap two elements and don't know which is more efficient. It seems like the runtime of both swaps are the same but I'm not too sure.

The only way to be sure is to write a proper micro-benchmark, run it (on a number of hardware platforms / Java versions) and interpret the results.

We can look at the source code, and make some informed guesses, but we cannot deduce micro-level efficiency from first principles1.

My advice:

  • Write the code in the way that you think is most readable, and let the compilers do the optimization. They can typically do a better job than most programmers.
  • If performance of your application is a concern, then write an application benchmark and use a profiler to find out where the real performance hotspots are.
  • Use the hotspot information to decide where it is worthwhile expending effort in hand-tuning the application ... not your intuition / guesswork.

1 - ... unless there is someone here with an unhealthily detailed amount of knowledge in their heads about how real world Java JIT compilers actually work across multiple platforms. And if there is someone here like that, we should probably just let them rest quietly, rather than bugging them with questions like this :-)

How do I Implement swap array method in main class?

Given below is a sample implementation:

class Array {
public static void swap(int i, int j, int[] array) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

/**
*
* Displays elements of the array from the end to the beginning
*/
public static void display(int[] array) {
// Use `for (int i =0; i <array.length; i++)` for forward navigation
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}

public class ArrayTest {
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
Array.display(arr);
Array.swap(0, 9, arr);
Array.display(arr);
}
}

Output:

10 9 8 7 6 5 4 3 2 1 
1 9 8 7 6 5 4 3 2 10

Notice that the static members are class members i.e. they are one per class as compared to non-static members which are one per instance. Therefore, static members should be accessed using the class name instead of using an instance e.g. Array.display as shown above.

Side note (because it won't affect the execution of your program): You should always follow Java naming conventions e.g. the class, array should be named as Array and the class, arrayTest should be named as ArrayTest. Also, try to avoid a name which has already been used in standard Java library e.g. you should choose a name other than Array.

[Update]

As promised, posting below a different implementation:

import java.util.Random;

class Array {
int[] array;

Array(int size) {
array = new int[size];
// Initialise the array with random elements from 0 to 100
Random random = new Random();
for (int i = 0; i < size; i++) {
array[i] = random.nextInt(100);
}
}

public void swap(int i, int j) {
if (i < 0 || j > array.length - 1) {
System.out.println("Indices should be in the range of 0 to " + (array.length - 1));
return;
}
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}

/**
*
* Displays elements of the array from the end to the beginning
*/
public void display() {
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + " ");
}
System.out.println();
}
}

public class ArrayTest {
public static void main(String[] args) {
Array arry = new Array(10);
arry.display();
arry.swap(0, 9);
arry.display();
arry.swap(0, 11);
}
}

Output from a sample run:

94 50 5 90 78 33 90 61 64 31 
31 50 5 90 78 33 90 61 64 94
Indices should be in the range of 0 to 9

Note that these are just a couple of sample implementations. I hope, it will help how you write your own implementation as per your requirement. Feel free to comment in case of any doubt/issue.

How can I swap each pair of values in an array in Java?

This should solve the problem.

for (int x = 0; x < array.length - 1; x = x + 2) {
int hold = array[x]; // So we don't lose it
array[x] = array[x + 1]; // Make the second one the first one
array[x + 1] = hold; // Make the second one the original first
}

Thank you, Jorn Vernee, for your recommendation.

Finding smallest integer in array, then swapping it with the first cell

It's a problem of pointer and values.

smallest = swap[i];

doesn't save the reference to the real item in the array swap[i]. In smallest you will find only the smallest value.
So, if you what to swap values, you have to save the index.
Here is the code

 import java.util.Scanner;
import java.util.Arrays;

public class swap {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);
System.out.println("Size of array?");
int n = sc.nextInt();

int [] swap = new int[n];
int index_smallest = 0;
int smallest = Integer.MAX_VALUE;
for(int i = 0; i <swap.length; i++){
System.out.println("Please enter a number: ");
swap[i] = sc.nextInt();

}
for(int i = 0; i < swap.length; i++){
if(smallest > swap[i]){
smallest = swap[i];
index_smallest = i;

}
}
int temp = swap[0];
swap[0] = swap[index_smallest];
swap[index_smallest] = temp;

System.out.println("\n");
for(int element : swap){

System.out.println(element);
}
}
}

How to swap entries efficiently in an Integer ArrayList in java

Use set to modify a value of an ArrayList:

nums.set(0, (nums.get(0)+nums.get(4))-(nums.set(4,nums.get(0));

However this code is hard to understand and I doubt that this (and the additional arithmetics) is worth saving a single swap variable.

For Strings, the - operator is not defined. But you could use the substring method. But this will make it even more complicated.



Related Topics



Leave a reply



Submit