-2

I need to use "maximum(int[] arr, int x, int y)" class (which finds maximum value in an integer array between from x to y) to get rid of temp in quicksort.

Briefly, during swap no temp element should be used.

my whole class is:

import java.util.Arrays;

public class qs {
    //divide and conquer for max value in an array from x to y
    static int maximum(int[] arr, int x, int y) {
        if (y - x <= 1) {
            return (Math.max(arr[x], arr[y]));
        } else {
            int max1 = maximum(arr, x, (x + y) / 2);
            int max2 = maximum(arr, (x + y) / 2 + 1, y);
            return Math.max(max1, max2);
        }

    } 

    static void quickSort(int[] arr, int l, int r){
        int i = l; int j = r; int temp;
        int a = arr[(l+r)/2];
        while(i<=j){
            while(arr[i] < a){
            i++;
            }
            while(arr[j]>a){
                j--;
            }

            if(i <= j){
                temp = arr[i];
                arr[i] = arr[j];
                arr[j] = temp;
                i++;
                j--;
                }
        }
            if(l<j){
                quickSort(arr, l, j);
            }
            if(i<r){
                quickSort(arr, i, r);
            }
    }

    public static void main(String[] args) {
        int[] arr = { 2, 17, -4, 42, 9, 26, 11, 3, 5, 28 };
        quickSort(arr, 0, 9);
        System.out.println("Quicksorted Array: " + Arrays.toString(arr));
    }

}
berkay
  • 1
  • 1
  • 1
    Why do you want to get rid of `temp`? – Oliver Charlesworth Nov 03 '14 at 00:22
  • 1
    God forbid your code stays -somewhat- readable. I believe there's some fancypantsy way to do it with XOR operators but do everyone a favor and don't seek any optimization in that area unless it's been very, very clearly deemed a problem. – Jeroen Vannevel Nov 03 '14 at 00:25
  • possible duplicate of [Is it possible to write swap method in Java?](http://stackoverflow.com/questions/1363186/is-it-possible-to-write-swap-method-in-java) – Kyborek Nov 03 '14 at 00:26
  • Don't. Just use the temp variable. Keeping it simple, gives the JIT the best working conditions. – Thorbjørn Ravn Andersen Nov 03 '14 at 00:29
  • You need to use that maximum how? There is no swap being performed there. – Elliott Frisch Nov 03 '14 at 00:30
  • I don't know how but my teacher says there is a possible way, and I can change maximum a little bit. And I just have to get rid of temp not swap. – berkay Nov 03 '14 at 00:33

1 Answers1

0

There is no reason to remove the temp variable. In fact, the compiler completely optimizes it away, and somehow finding a way of deleting it would probably make it run slower.

Tetramputechture
  • 2,911
  • 2
  • 33
  • 48