First, let's review the swap function design in C language
Pass-by-value: Can't fundamentally exchange two numbers
#include <stdio.h> void swap(int a, int b) { int temp; temp = a; a = b; b = temp; }
Bibliography: In C language, the address should be called
#include <stdio.h> void swap(int &a, int &b) { int temp; temp = a; a = b; b = temp; }
That's the problem. There is no pointer in Java, and there is no reference to ordinary variables. How do we pass references to ordinary types of variables?
Method 1: Use array
public static void swap(int[] data, int a, int b) { int temp; temp = data[a]; data[a] = data[b]; data[b] = temp; }
Method two (misleading): Pass the reference through the packaging class Integer in java, the result: failure, because the packaging class in java does not allow to change the data field, personally understand: java will not provide the packaging class Integer data address, that is, reference, But provide surface data
Method 3: Define your own packaging class MyInteger
static class MyInteger { private int x; public MyInteger(int x) { this.x = x; } public int getValue(){ return x; } public void changeValue(int x) { this.x = x; } } public static void swap(MyInteger a, MyInteger b) { int t = a.getValue(); a.changeValue(b.getValue()); b.changeValue(t); }
Method 4: External inline, use this class directly
public class Sort { int a, b; public Sort(int a, int b) { this.a = a; this.b = b; } public void swap() { int temp; temp = a; a = b; b = temp; } }
Above, personal reference
: https://blog.csdn.net/dadoneo/article/details/6577976