0

I am just trying to know how this code still works while the methods selection, insertion, bubble return void. Is it because the methods are static or what?

Also, how can one swap variables without XOR'ing them?

public class Sorts {

static int[] a = { 100, 90, 70, 60, 50, 40, 30, 20, 10, 7, 6, 5, 4, 3, 2, -1 };

public static void main(String[] args) {
    // TODO Auto-generated method stub

    bubbleSort(a);// Worst one
    print(a);

    int[] b = {100, 90, 70, 60, 50, 40, 30, 20, 10, 7, 6, 5, 4, 3, 2, -1};

    MY_SEMI_SELECTION_Sort(b);
    print(b);

    int[] e = { 100, 90, 70, 60, 50, 40, 30, 20, 10, 7, 6, 5, 4, 3, 2, -1};
    selectionSort2(e);
    print(e);

    int[] c = {100, 90, 70, 60, 50, 40, 30, 20, 10, 7, 6, 5, 4, 3, 2, -1};
    insertionSort(c); // The best so far
    print(c);

}

static void insertionSort(int[] arr) {

    int len = arr.length;

    for (int i = 1; i < len; ++i) {

        int j = i;

        while (j > 0 && arr[j] < arr[j - 1]) {
            // Swap
            arr[j] ^= arr[j - 1] ^= arr[j];
            arr[j - 1] ^= arr[j];

            --j;
        }
    }

}

static void MY_SEMI_SELECTION_Sort(int[] arr) {

    int len = arr.length;

    for (int i = 0; i < len; ++i) {

        for (int k = i; k < len - 1; ++k) {

            if (arr[i] > arr[k + 1]) {
                // Swapping........
                arr[i] ^= arr[k + 1] ^= arr[i];
                arr[k + 1] ^= arr[i];

            }

        }

    }

}

static void selectionSort2(int[] arr) {

    int len = arr.length;

    for (int i = 0; i < len; ++i) {

        int k;
        int minIndex = i;

        for (k = i; k < len - 1; ++k) {

            if (arr[minIndex] > arr[k + 1]) {
                minIndex = k + 1;
            }

        }

        if (arr[minIndex] != arr[i]) {
            arr[minIndex] ^= arr[i] ^= arr[minIndex];
            arr[i] ^= arr[minIndex];
        }

    }

}

static void bubbleSort(int[] arr) {

    int len = arr.length;

    for (int i = 0; i < len; ++i) {

        for (int k = 0; k < len - 1; ++k) {

            if (arr[k] > arr[k + 1]) {
                // Swapping........
                arr[k] ^= arr[k + 1] ^= arr[k];
                arr[k + 1] ^= arr[k];

            }

        }

    }

}

static void swap(int a, int b) {

    int temp = b;
    b = a;
    a = temp;
}

static void print(int[] arr) {

    int len = arr.length;

    for (int i = 0; i < len; ++i) {
        System.out.print(arr[i] + " ");
    }
    System.out.println();
  }

}
Matt C
  • 4,470
  • 5
  • 26
  • 44
Razorbolt
  • 47
  • 1
  • 8
  • Why are you surprised that it's working returning void...? – Luigi Cortese Mar 06 '16 at 17:27
  • The values of `Object`(s) in Java are **references**. Thus the values passed in arrays (arrays which are themselves `Object`s), can be modified in the method. – Elliott Frisch Mar 06 '16 at 17:29
  • Maybe I wasn't clear enough, the array changes after the method does some changes on it, it's a passing-by-value after all, right? @LuigiCortese – Razorbolt Mar 06 '16 at 17:30
  • @ElliottFrisch so what about the method swap? int isn't an Object?! – Razorbolt Mar 06 '16 at 17:31
  • Hmm, Java is always pass by value. – markspace Mar 06 '16 at 17:31
  • It is pass-by-value. But what *value* are we talking about? The value being passed to the functions is the **reference's value**, imagine it like the address of where the array is located. So, you're always referring to the same array. – Luigi Cortese Mar 06 '16 at 17:32
  • 1
    @Razorbolt Correct. But the array `arr` is the same array that was passed to the method. – Elliott Frisch Mar 06 '16 at 17:32
  • Also, `static` has nothing to do with value vs. reference. – markspace Mar 06 '16 at 17:33
  • @ElliottFrisch I didn't get the last you said, Also I tried the wrapper class Integer in passing the parameters to the method swap and yet it didn't work – Razorbolt Mar 06 '16 at 17:37
  • @LuigiCortese Okay with arrays I find that sensible enough, but what about the method swap, and how to get it working? – Razorbolt Mar 06 '16 at 17:38
  • @Razorbolt Wrapper types (and `String`) are **immutable** (you can't modify the caller's *reference*). As for the array, it's being passed by the value of a reference because arrays (in Java) are **not** primitive types. An `int[]` is a type of `Object` that can hold a fixed number of `int`(s). – Elliott Frisch Mar 06 '16 at 17:40
  • @Razorbolt I answered your question, definitely easier – Luigi Cortese Mar 06 '16 at 17:43

2 Answers2

2

Why are my methods working even though they return void?

Java is always pass-by-value. But what value are we talking about? The value being passed to the functions is the reference value, imagine it like the address of where the array is located. So, you're always referring to the same array, both inside and outside your methods.

How to swap elements without Xoring them?

Imagine variables as buckets, you cannot fill one without losing its previous content. You need to use a temporary variable

int a=1,b=2;
int tmp=a;
a=b;    //without the previous line of code you'd have lost the value of 'a'
b=tmp;
Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48
  • I mean through a method to make my code tidy, since I use it a lot. Any thoughts? – Razorbolt Mar 06 '16 at 17:49
  • do you really need to use a function to substitute two lines of code? – Luigi Cortese Mar 06 '16 at 17:50
  • In long term, definitely YES. – Razorbolt Mar 06 '16 at 17:51
  • @Razorbolt it's going to be longer than you think, you're swapping primitives. For primitives, values are... original values, not reference values. I mean, in your helper method you'd get copies of your original variables, you would'nt be able to swap values of primitive variables external to the function. Read [this](http://stackoverflow.com/questions/1363186/is-it-possible-to-write-swap-method-in-java/1363200#1363200) – Luigi Cortese Mar 06 '16 at 17:54
  • Pass the array are the first parameter to your `swap` method. Then you can swap arbitrary index values with a `temp`. – Elliott Frisch Mar 06 '16 at 17:57
  • This works perfectly. static void swap(int[] arr, int a, int b) { int temp = arr[a]; arr[a] = arr[b]; arr[b] = temp; } – Razorbolt Mar 06 '16 at 17:58
  • it's okay @LuigiCortese I want to accept it but I need users to see the comments also not just the answer I preferred. you get me, right? – Razorbolt Mar 06 '16 at 22:45
-1

is it because the methods are STATIC No, because int array a is a reference only. While calling different methods the same reference is passed as parameter. Even result will be the same if int array a is local variable to main.

how to swap elements without Xoring them The best way to swap variables is via XOR.

a = a ^ b;
b = a ^ b;
a = a ^ b;

The other way is via using temp variable.

Hemant Patel
  • 3,160
  • 1
  • 20
  • 29
  • **Without** xoring them. – Elliott Frisch Mar 06 '16 at 17:34
  • Yes, without Xor-ing. – Razorbolt Mar 06 '16 at 17:40
  • it's also notable that the first may cause an integer overflow at some point. – Razorbolt Mar 06 '16 at 17:45
  • Good thinking, sir @ElliottFrisch But I'm most interested in doing that via a method to make the code tidy since I use swapping a lot. – Razorbolt Mar 06 '16 at 17:46
  • The second one is fine (using t). But the first one has a flaw, when a + b crosses Integer.MAX_,VALUE – Hemant Patel Mar 06 '16 at 17:46
  • Write a method something like this, void swap(int a[], int i, int j) { int t = a[¡]; a[i] = a[j]; a[j] = t; } – Hemant Patel Mar 06 '16 at 17:48
  • @Hemant it worked and I guess I know understand, you have to pass the array to get them modified. Much thanks – Razorbolt Mar 06 '16 at 17:56
  • There is no need to show how to swap with XOR, he obviously knows how to do that. Instead, you should show what he asked for, which was WITHOUT XOR. And you shouldn't say that the BEST way to swap is with XOR without saying why that is. – Matt C Mar 06 '16 at 20:14
  • You should also see what was the intension, why he chose no to use XOR. He wanted to move into a swap method as he was doing swapping via XOR at multiple places. In above comment I told him how to move into a method. Even XOR can also be used in the method directly using a[i] and a[j]. Next Xor is best as it doesn't take any extra memory and bitwise operations are cheaper so i think this is the best way to swap variables – Hemant Patel Mar 08 '16 at 02:52