2

I have the following code which is working fine , but can anybody tell me how to change the alogirithm to use random pivot element.

instead of below , i want to select pivot element randomly , any help will be appreciated

      int pivot = arr[(left + right) / 2];

import java.util.Random;


public class QuickSort {

    /**
     * @param args
     */
    public static void main(String[] args) {

          int i;
          int array[] = {10,9,1,2,3,4,100,200,300,400};  
          System.out.println(" Quick Sort\n\n");
          System.out.println("Values Before the sort:\n");
          for(i = 0; i < array.length; i++)
          System.out.print( array[i]+"  ");
          System.out.println();
          quickSort(array,0,array.length-1);
          System.out.print("Values after the sort:\n");
          for(i = 0; i <array.length; i++)
          System.out.print(array[i]+"  ");
          System.out.println(); 

    }

    public static int partition(int arr[], int left, int right)
    {
          int i = left, j = right;
          int tmp;



          int pivot = arr[(left + right) / 2];

          while (i <= j) {
                while (arr[i] < pivot)
                      i++;
                while (arr[j] > pivot)
                      j--;
                if (i <= j) {
                      tmp = arr[i];
                      arr[i] = arr[j];
                      arr[j] = tmp;
                      i++;
                      j--;
                }
          };

          return i;
    }

    public static void quickSort(int arr[], int left, int right) {
          int index = partition(arr, left, right);
          if (left < index - 1)
                quickSort(arr, left, index - 1);
          if (index < right)
                quickSort(arr, index, right);
    }

}
1
  • What's with the genetic-algorithm tag? I don't see how you are using genetic algorithms here, or what benefit they would bring. Commented Sep 17, 2011 at 6:38

1 Answer 1

6

Replace the pivot variable assignment with:

int pivot = arr[left + rnd.nextInt(right - left)];

where rnd is a class Random object, which you could set as a private static final field.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks per , let me give as try

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.