QuickSort Problems

I am trying to write a QuickSort to sort an ArrayList of random integers passed from another class. If it is given 5 2 7 6 9 0 8 1 3 4 it finishes with the ArrayList holding 0 1 2 4 3 5 7 6 8 9
is this a problem with my logic or just a minor programming error? I am using the first item in the ArrayList as the pivot, partitioning, and then swapping the pivot into position and recursively running quicksort(start,pivot-1) and quicksort(pivot+1,end)
import java.util.*;
public class QuickSort
ArrayList<Integer> data;
public QuickSort(ArrayList<Integer> datax)
data=datax;
public void quicksort(int start, int end)
if (start < end)
int pivot = partition(start, end);
quicksort(start, pivot-1);
quicksort(pivot+1, end);
public int partition(int start, int end)
int pivot = data.get(start);
int l = start + 1;
int r = end;
while (l < r)
while (l < end && data.get(l) < pivot) l++;
while (r > start && data.get(r) >= pivot) r--;
if (l < r)
swap(l,r);
swap(start,r);
return r;
public void swap(int index1, int index2)
int temp=data.get(index1);
data.set(index1,data.get(index2));
data.set(index2,temp);
}

What happens when your partition method is passed a range that contains two numbers that are already sorted?

Similar Messages

  • QuickSort Problem

    Alright, so I'm trying to do a quicksort for ArrayLists and here is what I have but I keep getting StackOverFlowErrors. I've been looking at it for an hour and this all makes sense to me but I'm missing how it's overflowing. Any help?
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.Iterator;
    import java.util.Random;
    public class QuickSort<E>{
         public ArrayList<E> sort(ArrayList<E> list, Comparator<E> c) {
              Random random = new Random();
              ArrayList<E> list2 = new ArrayList<E>();
              int pivotIndex = random.nextInt(list.size());
              for (Iterator<E> it = list.iterator(); it.hasNext(); )
                   E next = it.next();
                   if(c.compare(next,list.get(pivotIndex))==-1)
                        list2.add(next);
                        it.remove();
              ArrayList<E> firstHalf;
              ArrayList<E> secondHalf;
              if(list2.size()>1)
                   firstHalf = sort(list2, c);
              else
                   firstHalf = list2;
              if(list.size()>1)
                   secondHalf = sort(list, c);
              else
                   secondHalf = list;
              for(int i = 0;i<secondHalf.size();i++)
                   firstHalf.add(secondHalf.get(i));
              return firstHalf;
    }

    Here's an authentic implementation of the quicksort algorithm. You should notice that:
    1) You should not need another lists to make. Use only the original list throughout.
    2) If you could use arbitrary value from the list as pivot, you don't need to use random number.
    3) You should not need to check the element sequence in any sublist(s) at each recursive call because the proper repositioning(swapping) of the pivots makes a correct ordering of list elements for you. (*)
    *: Edited later -- Your bad bad QuickSort.java could mimic this technique.
    /* save and compile as QuickSortCorrect.java and
    * run it as QuickSortCorrect
    import java.util.*;
    public class QuickSortCorrect<E>{
      ArrayList<E> list;
      Comparator<E> comp;
      public QuickSortCorrect(ArrayList<E> al, Comparator<E> c){
        list = al;
        comp = c;
      public ArrayList<E> getSorted(){
        sort(0, list.size() - 1);
        return list;
      public void sort(int left, int right) {
        if (right - left <= 0){
          return;
        else{
          E pivot = list.get(right);  //right-most val, == an arbitrary value
          int partp = partition(left, right, pivot);
          sort(left, partp - 1);  // leave previous pivot that is now
          sort(partp + 1, right); // in the correct position in the list
      /* make partitioning and return the partition index */
      int partition(int left, int right, E pivot){
        E temp;
        int leftp = left - 1; // first ++ get <left>
        int rightp = right; // right == always pivot, so first -- get <right - 1>;
        while(true){
          while (comp.compare(list.get(++leftp), pivot) < 0){
          while (rightp > 0 && comp.compare(list.get(--rightp), pivot) > 0){
          if (leftp >= rightp){
            break;
          else{ // swap smaller <-> bigger
            temp = list.get(leftp);
            list.set(leftp, list.get(rightp));
            list.set(rightp, temp);
        temp = list.get(leftp); // use this as next pivot, == arbitrary
        list.set(leftp, list.get(right)); // move current pivot to its correct pos
        list.set(right, temp);            // set next pivot at right-most
        return leftp;
      /* main() for test */
      public static void main(String[] args){
        ArrayList<String> ars = new ArrayList<String>();
        ars.add("850");
        ars.add("126");
        ars.add("030");
        ars.add("254");
        ars.add("110");
        ars.add("574");
        ars.add("920");
        ars.add("574");
        ars.add("182");
        ars.add("052");
        ars.add("423");
        ars.add("126");
        ars.add("574");
        ars.add("166");
        ars.add("774");
        QuickSortCorrect<String> qs
         = new QuickSortCorrect<String>(ars, new Comparator<String>(){
          public int compare(String s1, String s2){
            return s1.compareTo(s2);
        ars = qs.getSorted(); // get result
        for (String s : ars){
          System.out.println(s);
    }Edited by: hiwa on 2008/03/18 18:53

  • Java Linear, Quicksort, Binary Time Calc Problems

    Objective of program: Simple program demonstrating the time it takes to do each algorithm.
    My approach:
    1) Prompt a number
    2) Make array of linear ints
    3) Calculate time it takes for a linear search
    4) Repeat for quick sort, and Binary search
    Problems:
    1) Linear search time is always 0
    2) Quick sort never ends.
    3) Don't know if binary works yet since it never goes beyond quicksort.
    Any help or suggestions are greatly appreciated.
    import java.util.Date;
    import java.util.ArrayList;
    import java.util.Random;
    import java.util.Arrays;
    import java.util.Scanner;
    public class Driver {
         public static void main(String[] args) {
              Random generator = new Random();               
              int[] linear = new int[1000000];                           // Create Linear Array
              for(int i = 0; i < linear.length; i++)                 // filling up the array
                   linear[i] = i;
              Scanner input = new Scanner(System.in); 
              System.out.print("Please enter number to search: ");       // Asks
              int search = input.nextInt();                              // Stores number
              Date end = new Date();                                   // Create Timer          
              long startTime1 = end.getTime();                           // Start Time
              for(int i = 0; i < linear.length; i++) {               // Linear Search
                   if (linear[i] == search) {
                        long endTime1 = end.getTime();                 // If found, end time
                        System.out.println("Time of Linear search: " + (endTime1 - startTime1));          // Prints elapsed time
                        break;
              int[] quicksort = new int[1000000];                    // Creates quicksort array
              for(int i = 0; i < quicksort.length; i++)                // Initializes the array
                   quicksort[i] = generator.nextInt(100000);
              long startTime2 = end.getTime();                         // Starts the time
              for(int i = 0; i < 1000000; i++)                         // Sorts...
                   Arrays.sort(quicksort);
              long endTime2 = end.getTime();                         // Ends time
              System.out.println("Time of QuickSort: " + (startTime2 - endTime2));               // Prints elapsed time
              int[] binary = new int[1000000];                         // Creates binary array
              for(int i = 0; i < binary.length; i++)                    // Initializes binary array
                   binary[i] = generator.nextInt();
              long startTime3 = end.getTime();                         // Start time
              Arrays.binarySearch(binary,search);                      // Binary Search
              long endTime3 = end.getTime();                         // Ends time
              System.out.println("Time of Binary Search: " + (endTime3 - startTime3));     // Prints out time
    }Edited by: onguy3n on Mar 26, 2009 4:39 AM

    ibanezplayer85 wrote:
    Any help or suggestions are greatly appreciated.
    Suggestion: Break your code up into different methods and even separate classes, if necessary; don't just use main for everything. Maybe you posted it this way to have it all in one class for the forum to read, but it's very confusing to look at it and understand it this way. I know that this isn't an answer to your question, but you did ask for suggestions :)Thanks, it was just a demonstration program in class so he didn't really care about readability, but yes I should have separated it in a different class.
    >
    Linear search time is always 0I'm not sure what the convention is, but whenever I needed to measure time for an algorithm, I used System.currentTimeMillis(); rather than the Date class.
    e.g.
    long startTime = System.currentTimeMillis();
    long endTime = System.currenTimeMillis();
    long totalTime = endTime - startTime;Although, I think if you're not printing anything out to the console, it will most likely print out 0 as the time (because most of the processing is working on printing out the data). That is, unless you're doing some heavy processing.Thanks! I tried System.currentTimeMillis() and it now works. I still don't understand your explanation why it prints out 0 though :(
    >
    Quick sort never ends.I think it's just taking a while. It's not an efficient algorithm with a worst case time complexity of O(n^2) and you gave it a very large array of random values to work with. I wouldn't be surprised if you ran out of heap space before it finished. If you knock off some zero's on the array size, you'll see that it does, in fact, finish.Ok, thanks! In class we didn't talk much about the heap. How do I calculate how much heap space my program will use and how to allocate more? I vaguely remember something like xmx512m or something as the parameter, but every time I get an error:
    Unrecognized option: -xmx512m
    Could not create the Java virtual machine.

  • Problems defining the array for quicksort

    import java.io.*;
    import java.util.*;
    import chn.util.*;
    public class Store
              private Item [] myStore;
              public Store (String fileName) {
                   fileName = "file50.txt";
    /*          public void displayStore ()       
              public String toString () { }
              public void doSort () { }
    */          private void quickSort (Item[] lit, int lo, int hi)   // I don't exactly know what Item[ ] lit will do. please explain it for me.
              int h, l, p, t;
            if (lo < hi) { 
                l = lo;
                h = hi;
          /*      p = a[hi];     //my problem starts with the array 'a' (suppose to be item, but don't know how to modify that.
                do {
                    while ((l < h) && (a[l] <= p)) l++;
                    while ((h > l) && (a[h] >= p)) h--;
                    if (l < h) {
                        t = a[l];
                        a[l] = a[h];
                        a[h] = t;
                } while (l < h);
                t = a[l];
                a[l] = a[hi];
                a[hi] = t;
              private void loadFile (String inFileName)
                   FileInput inFile = new FileInput (inFileName = "file50.txt");
    }The array 'a' should be replaced with the array 'Item' but some how I'm getting the errors that Item's not a valid type.
    for more information, please see http://forum.java.sun.com/thread.jspa?threadID=699397&tstart=60 for more information (the original problem)

    Here is what I suggest.
    Use collections. I suggest an ArrayList. Using one array involves all sort of messy swapping around which really will make things difficult for you to grasp the basic concept of.
    So let us assume a method like this
    public void quicksort(List items)
    items is a List of Items.
    So here is how to write a quicksort
    1) If the size of the list is 1 then return the list because it is down to it's final piece and doesn't need to be sorted further
    2) Choose a pivot element of your list. The mid point is often chosen for this.
    3) Create two new Lists. One for lower elements and one for higher and equal to elements.
    4) Go through the list and use compareTo to compare the elements of the list with your pivot element. Take care to skip the pivot element. If elements are less than the pivot put them in the first list. If they are more than or equal to put them in the second list.
    5) Recursively call quicksort(list) on the sublists we made.
    6) Merge the sublists and pivot values back into one list
    7) return the merged list

  • Problem With Quicksorting a Vector

    Hi there!
    I tried to write an extended Vector which can perform a quicksort of itself.
    Unfortunately, after the quicksort, everything int his Vector seems "damaged" - although I get the right Strings out of it, the don't seem to be internally right. ANyway, I'll post my code here and hope anyone can tell me what is wrong with it ;-)
    public class SortingVector extends java.util.Vector {
         public SortingVector() {
              super();
         public SortingVector(int i, int j) {
              super(i, j);
         public void sortStrings() {
              quickSortStrings(0, this.size() - 1);
         private void quickSortStrings(int l, int r) {
              if (l < r) {
                   int r2 = partitionStrings(l, r);
                   quickSortStrings(l, r2);
                   quickSortStrings(r2 + 1, r);
         private void exchange(int m, int n) {
              Object o1 = this.elementAt(m);
              this.set(m, this.elementAt(n));
              this.set(n, o1);
         private int partitionStrings(int m, int n) {
              String x = ((String) this.elementAt(m)).toLowerCase(); // Pivot-Element
              int j = n + 1;
              int i = m - 1;
              while (true) {
                   j--;
                   while (checklarger(j, x)) {
                        j--;
                   i++;
                   while (checksmaller(i, x)) {
                        i++;
                   if (i < j)
                        exchange(i, j);
                   else
                        return j;
         private boolean checklarger(int j, String x) {
              int count = 0;
              String element = ((String) this.elementAt(j)).toLowerCase();
              while ((element.charAt(count) == x.charAt(count))
                   && (count < element.length() - 1)
                   && (count < x.length() - 1)) {
                   count++;
              if (element.charAt(count) > x.charAt(count)) {
                   return true;
              return false;
         private boolean checksmaller(int j, String x) {
              int count = 0;
              String element = ((String) this.elementAt(j)).toLowerCase();
              while ((element.charAt(count) == x.charAt(count))
                   && (count < element.length() - 1)
                   && (count < x.length() - 1)) {
                   count++;
              if (element.charAt(count) < x.charAt(count)) {
                   return true;
              return false;

    Unfortunately, after the quicksort, everything int his
    Vector seems "damaged" - although I get the right
    Strings out of it, the don't seem to be internally
    right.I also think you should use the built-in sort but what do you mean by "damaged"?

  • Stack OverFlow Problem with QuickSort Partition, please help.

    I have a Quicksort method that keeps running into a Stack OverFlow error when it attempts to partition.
    Here are my methods:
    public static void quickSort(int[] a){
              int from = 0;
              int to = a.length - 1;
              sort(a, from, to);
    private static int partition(int[] a, int from, int to){  
              int pivot = a[from];  
              int i = from - 1; 
              int j = to + 1;  
              while (i < j){
                   i++; while (a[i] < pivot) i++;     
                   j--; while (a[j] > pivot) j--;     
                   if (i < j) swap(a, i, j);    
              return j;
         private static void sort(int[] a, int from, int to){  
              if (from >= to) return;  
              int p = partition(a, from, to); // eclipse tells me my error is here.
              sort(a, from, p);  
              sort(a, p + 1, to); // I also have an error here.
         }Eclipse points to the sort method as the source of my error, which itself points to my attempting to partition the sucker, so I don't know what's up. It's probably something stupid, but I'm lost, so any help is appreciated.

         private static void swap(int[] a, int i, int j){
                   int temp = a;
              a[i] = a[j];
              a[j] = temp;
              }The quicksort method works until the array size is greater than 9723. That's when I get my overflow error.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Problems quicksorting my linkedlist (extention from other thread)

    Ok so now that I've got my concepts down I went to do a sort method and I'm having problems with my sort method. (the previous thread with my actual class is http://forum.java.sun.com/thread.jspa?messageID=10222048)
    Here is the sort method. Can anyone help me figure out what I'm doing wrong? (for reference..I'm getting a NullPointerException somewhere)
    public WordList sort()
              Node pivotNode=head;
              remove(head.data);
              WordList small = new WordList(br);
              WordList big = new WordList(br);
              Node first = head;
              while(first!=null)
                   if(first.data.compareTo(pivotNode.data)<0)
                        small.add(first.data);
                   else
                        big.add(first.data);
                   first=first.next;
              big.addToFront(pivotNode.data);
              small = small.sort();
              big = big.sort();
              while(big.head!=null)
                   small.add(big.head.data);
                   big.head=big.head.next;
              return small;
         }

    remove(head.data);
    Node first = head;
    if(first.data.compareTo(pivotNode.data)<0)Looking at those statements in order, I see the possiblity for a problem with null.
    Wouldn't first.data be null?
    Edited by: Newworld20 on Apr 24, 2008 3:42 PM

  • What is wrong in this Quicksort method??

    Please go through the program and tell me what is wrong with the method Quicksort? Thanx.
    The program:
    public class Main {
    * @param args the command line arguments
    public static void main(String[] args) {
    int[] unsorted = {9,5,6,1,3,8,9,7,5,3,5,3,13};
    unsorted = Quicksort(unsorted,unsorted.length/2,unsorted.length-1);
    for(int i=0;i<unsorted.length;i++)
    System.out.print(unsorted[i]+" ");
    public static int[] Quicksort(int[] input, int pivot, int end)
    if(pivot>0)
    int[] right =new int[pivot-0];
    int[] left =new int[end-pivot];
    int[] sortedArray = new int[1000];
    int lft=0,rht=0;
    for(int i=0;i<end;i++)
    if(input[pivot]<input)
    right[rht++]=input[i];
    else if(input[pivot]>input[i])
    left[lft++]=input[i];
    left = Quicksort(left,lft/2,lft);
    right = Quicksort(right,rht/2,rht);
    int i;
    for(i=0;i<lft;i++)
    sortedArray[i]=left[i];
    i++;
    sortedArray[i]=input[pivot];
    for(int j=0;j<rht;j++)
    sortedArray[j+i]=right[j];
    return sortedArray;
    else
    return null;
    the errors:
    Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
    at qsort.Main.Quicksort(Main.java:39)
    at qsort.Main.main(Main.java:19)
    Java Result: 1
    39: left[lft++]=input[i];
    19: unsorted = Quicksort(unsorted,unsorted.length/2,unsorted.length-1);

    When posting code, make sure you use the CODE tags to preserve formatting.
    But I can tell you right now that your problem is exactly what the error message tells you it is. Step through to figure out why that happens, something is wrong in your logic.

  • Help with quicksort

    Hey Guys could anyone help me out?
    I have this selection sort but i'm struggling to get a quick sort...
    class sort
    // method to display the contents of an array
         static void displayData(int[] data)
              for (int index=0; index != data.length; index++)
                   System.out.println(data[index]+"\t");
    // The method for sorting the numbers
        static void selectionSort(int[] data)
             int currentMax;
             int currentMaxIndex;
             for (int i=data.length-1; i>=1; i--)
    // Find the maximum in the list[0..i]
               currentMax = data;
         currentMaxIndex = i;
         for (int j=i-1; j>=0; j--)
    if (currentMax < data[j])
    currentMax = data[j];
    currentMaxIndex = j;
    // Swap list[i] with list[currentMaxIndex] if necessary;
    if (currentMaxIndex != i)
    data[currentMaxIndex] = data[i];
    data[i] = currentMax;
    public static void main(String[] args)
              int[] data = {18,7,15,8,13};
              int[] moreData = {8, 5, 9, 22, 3, 8};
              System.out.println("numbers before being sorted\n");
              displayData(data);
              selectionSort(data);
              System.out.println("numbers after being sorted using selection sort\n");
              displayData(data);
              System.out.println("\n\nnumbers before being sorted\n");
              displayData(moreData);
              System.out.println("numbers after being sorted using quicksort\n");
              displayData(moreData);     
    }If anyone knows how to do a quick sort it would really help. 
    thank you for your time guys and girls
    Dave                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    ok i've progressed... here's what i have now.
    (now the only problem i have is that the quick sorted numbers dont apper (any suggestions?))
    class sort
         // method to display the contents of an array
         static void displayData(int[] data)
              for (int index=0; index != data.length; index++)
                   System.out.println(data[index]+"\t");
         // The method for sorting the numbers
        static void selectionSort(int[] data)
             int currentMax;
             int currentMaxIndex;
             for (int i=data.length-1; i>=1; i--)
         // Find the maximum in the list[0..i]
               currentMax = data;
         currentMaxIndex = i;
         for (int j=i-1; j>=0; j--)
    if (currentMax < data[j])
    currentMax = data[j];
    currentMaxIndex = j;
         // Swap list[i] with list[currentMaxIndex] if necessary;
    if (currentMaxIndex != i)
         data[currentMaxIndex] = data[i];
         data[i] = currentMax;
    //Quicksort method
         static void quickSort (int[] moreData, int left, int right)
              if (left < right)
                   int p = partition(moreData, left, right);
                   quickSort(moreData, left, p-1);
                   quickSort(moreData, right, p+1);          
         //partition method
         static int partition (int[] moreData, int left, int right)
              int pivot = moreData [left];
              int p = left;
              for (int r = left+1; r <= right; r++)
                   if(moreData[r] < pivot)
                        moreData[p] = moreData[r];
                        moreData[r] = moreData[p+1];
                        moreData[p+1] = moreData[pivot];
                        p++;
              return p;
    }and this is the code in my driver class sortDriver
         public static void main (String args [])
              int[] data = {18,7,15,8,13};
              int[] moreData = {8, 5, 9, 22, 3, 8};
              System.out.println("numbers before being sorted\n");
              sort.displayData(data);
              sort.selectionSort(data);
              System.out.println("numbers after being sorted using selection sort\n");
              sort.displayData(data);
              System.out.println("\n\nnumbers before being sorted\n");
              sort.displayData(moreData);
              sort.quickSort(moreData,0,moreData.length-1);
              System.out.println("numbers after being sorted using quicksort\n");
              sort.displayData(moreData);     
    ps sorry about the lower case class names :P                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Sorting with TreeMap vs. quicksort

    I've been sorting lists by throwing them into a TreeMap then retrieving them in order (especially for fairly evenly distributed lists of strings), thereby leveraging its binary tree characteristics.
    My belief is that sorting this way takes N log N time, just as quicksort (as in Arrays.sort) does -- because adding items to a TreeMap takes log N time -- without any danger of stack overflows from recursing on a huge list as with quicksort, and fewer method calls which can get expensive.
    I'm figuring that even if this way of sorting uses more memory than an in-place sort as in Arrays.sort, at least it won't overflow the stack, and will mostly be eligible for garbage collection anyway.
    Could someone correct or confirm my conclusions, reasoning or assumptions? And how well do they apply to Collections.sort's merge sort?

    Using a tree guarentees worst case O(n log n) for n
    inserts.Amazing, my untrained intuition was correct.
    As for stack problems these are unlikely to occur until
    logn is at least a few thousand (think about stupidly large values of
    n).I regularly need to sort lists of tends of thousands of strings.
    .. its [quicksort's] gotcha is that
    performance can degrade well below this approaching
    O(n^2) (might be higher. I cant remember).Yes, O(n^2) for adversarial data. Does mergesort require a shallower recursion than quicksort does?
    Since temporary use of the heap is rarely a concern for me, and datasets are very large, it sounds like mergesort and the TreeMap are viable contenders for preferred sorting methods. But I'm still apprehensive about mergesort's use of recursion.
    Thank you, I gave you 5 duke dollars and matei 2.

  • Quicksort with Median of Medians Method.

    I am trying to test the MM, (Median of Medians method), to see that it has O(n) complexity. I can not get it to work, it is in part because I don't understand how to incorperate the MM code in to the Quicksort Method. Also note that there is an error in my Quick sort, the list sorts to some extent. I am trying to figure that out. So, all in all I have two problems... Here is what I have:
    public class MMQuickSort
         private static long comparisons = 0;
         private static long exchanges = 0;
         static final int numberofgroups = 5;
         private static int groupsize = 0;
              public static void Quicksort(int[] a)
                   // shuffle(a);           // to guard against worst-case and makes average = best = O(nlogn) without MM.
                    groupsize = a.length / numberofgroups;
              QuickSort(a, 0, a.length);
         public static void QuickSort(int[] inarray, int low, int high)
              int thepivot, position = 0;
                   if (low < high)
                        thepivot = Partition(inarray, low, high, high - 1);
                        QuickSort(inarray, low, thepivot - 1);
                        QuickSort(inarray, thepivot + 1, high);
         public static int Partition(int[] inarray, int low, int high, int pivot)
              int v = inarray[low];
              int j = low;
              int temp;
              //int moveleft = high + 1;
              //int v = inarray[low];
              for (int i = low + 1; i < high; i++)
                   if (inarray[i] < v)
                        j++;
                        temp = inarray;
                        inarray[i] = inarray[j];
                        inarray[j] = temp;
                   pivot = j;
                   temp = inarray[low];
                   inarray[low] = inarray[pivot];
                   inarray[pivot] = temp;
              return pivot;
         public static int Select(int a[], int n, int k)
              int pivot= 0;
              if (n <= numberofgroups)
                   Quicksort(a);
              else
                   pivot = Select(a, a.length / numberofgroups, ((int)Math.ceil(a.length / numberofgroups / 2)));
              if (k == pivot)
                   return k;
              else if (k < pivot)
                   return Select(a, pivot - 1, k);
              else
                   return Select(a, n - pivot, k - pivot);
    To get it to work I call:
    Quicksort(data) 
    where "data" is a dis-ordered array of n elements.
    Any thoughts would be much appreciated.
    Thank you,
    Brian                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    it would be good if you posted the exception next time
    the exception occurs in the partition() method, on the line
    while (less(a[++i], v)) ;it appears that l = 13 and r = 12, and a[++i] = a[13], a[14], a[15]... are all less than v = a[12]
    "l" probably shouldn't be greater than "r"
    on closer examination, it appears that your quicksort() algorithm has no base case. it keeps partitioning and making recursive calls until the subarray you are partitioning over has negative size (?)

  • Quicksort using Comparable can sort out negative value well !!

    man , i have waste another day try to solve this logic problem. It was not easy as what i thought. The Qsort method which i found it on the net and i apply it into my java code .. i do understand his code well , however the result does not sort out well especially negative number or if there is there are small number at the end of the array. Below are some result which i compile .Hope someone can help me , i going crazy soon.
    sample 1:
    Before Soft()
    [93, 50, 34, 24, -48, 27, 45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -37, -48, -71, -95, 11, 16, 2, 24, 27, 34, 45, 50, 51, 60, 93]
    sample 2:
    Before Soft()
    [-93, 50, -34, -24, 48, -27, -45, 11, 60, 51, -95, 16, -12, -71, -37, 2]
    After Soft()
    [-12, -24, -27, -34, -37, -45, -71, -93, -95, 11, 16, 2, 48, 50, 51, 60]
    sample 3 ==> this one is correct ;-)
    Before Soft()
    [93, 50, 34, 24, 48, 27, 45, 11, 60, 51, 95, 16, 12, 71, 37, 20]
    After Soft()
    [11, 12, 16, 20, 24, 27, 34, 37, 45, 48, 50, 51, 60, 71, 93, 95]
    import java.util.*;
    import java.lang.Comparable;
    public class QuickSort {
    // static Comparable [] array;
    public QuickSort(){}
    public static void main ( String [] args){
              QuickSort qs =new QuickSort ( );
              Object [] test = new Object [16];
              test[0]="93";
              test[1]="50";
              test[2]="34";
              test[3]="24";
              test[4]="-48";
              test[5]="27";
              test[6]="45";
              test[7]="11";
              test[8]="60";
              test[9]="51";
              test[10]="-95";
              test[11]="16";
              test[12]="-12";
              test[13]="-71";
              test[14]="-37";
              test[15]="2";
              for (int i=0;i<test.length;i++)
              System.out.println(test);
              System.out.println();
    /* Copy the value from the Object [ ]test into Comparable [] array. /*
    Comparable [] array = new Comparable [test.length];
    for(int i=0;i<array.length;i++)
         array [i]=(Comparable) test[i];          
         System.out.println(array[i]); //test if the value is the same as the test Object //
    System.out.println("Before Soft()");
    System.out.println(Arrays.asList(array));
    qs.sort(array); //call sort method to sort the array
    System.out.println("After Soft()");
         System.out.println(Arrays.asList(array));
    * Sorts the array of Comparable objects using the QuickSort algorithm.
    * @param comparable an array of java.lang.Comparable objects
    public void sort(Comparable comparable[]) {
    QSort(comparable, 0, comparable.length - 1);
    * @param comparable an array of java.lang.Comparable objects
    * @param lowInt int containing lowest index of array partition
    * @param highInt int containing highest index of array partition
    static void QSort(Comparable comparable[], int lowInt, int highInt) {
    int low = lowInt;
    int high = highInt;
    Comparable middle;
    // The partion to be sorted is split into two separate sections which are
    // sorted individually. This is done by arbitrarily establishing the middle
    // object as the starting point.
    if (highInt > lowInt) {
    middle = comparable[(lowInt + highInt) / 2];
    // Increment low and decrement high until they cross.
    while (low <= high) {
    // Increment low until low >= highInt or the comparison between
    // middle and comparable[low] no longer yields -1 (ie comparable[low]
    // is >= middle).
    while (low < highInt && (comparable[low].compareTo(middle) < 0)) {
    ++low;
    // Decrement high until high <= lowInt or the comparison between
    // middle and comparable[high] no longer yields 1 (ie comparable[high]
    // is <= middle).
    while (high > lowInt && (comparable[high].compareTo(middle) > 0 )) {
    --high;
    /*switch over */
    if (low <= high) {
    Comparable obj;
    obj = comparable[low];
    comparable[low] = comparable[high];
    comparable[high] = obj;
    ++low;
    --high;
    if (lowInt < high) {
    QSort(comparable, lowInt, high);
    if (low < highInt) {
    QSort(comparable, low, highInt);

    the problem is solve after cos i cast a string variable into the object comparable. The problem is solve after i use cast Integer into the object.
    regards
    st

  • A problem with threads

    I am trying to implement some kind of a server listening for requests. The listener part of the app, is a daemon thread that listens for connections and instantiates a handling daemon thread once it gets some. However, my problem is that i must be able to kill the listening thread at the user's will (say via a sto button). I have done this via the Sun's proposed way, by testing a boolean flag in the loop, which is set to false when i wish to kill the thread. The problem with this thing is the following...
    Once the thread starts excecuting, it will test the flag, find it true and enter the loop. At some point it will LOCK on the server socket waiting for connection. Unless some client actually connects, it will keep on listening indefinatelly whithought ever bothering to check for the flag again (no matter how many times you set the damn thing to false).
    My question is this: Is there any real, non-theoretical, applied way to stop thread in java safely?
    Thank you in advance,
    Lefty

    This was one solution from the socket programming forum, have you tried this??
    public Thread MyThread extends Thread{
         boolean active = true;          
         public void run(){
              ss.setSoTimeout(90);               
              while (active){                   
                   try{                       
                        serverSocket = ss.accept();
                   catch (SocketTimeoutException ste){
                   // do nothing                   
         // interrupt thread           
         public void deactivate(){               
              active = false;
              // you gotta sleep for a time longer than the               
              // accept() timeout to make sure that timeout is finished.               
              try{
                   sleep(91);               
              }catch (InterruptedException ie){            
              interrupt();
    }

  • A problem with Threads and MMapi

    I am tring to execute a class based on Game canvas.
    The problem begin when I try to Play both a MIDI tone and to run an infinit Thread loop.
    The MIDI tone "Stammers".
    How to over come the problem?
    Thanks in advance
    Kobi
    See Code example below:
    import java.io.IOException;
    import java.io.InputStream;
    import javax.microedition.lcdui.Graphics;
    import javax.microedition.lcdui.Image;
    import javax.microedition.lcdui.game.GameCanvas;
    import javax.microedition.media.Manager;
    import javax.microedition.media.MediaException;
    import javax.microedition.media.Player;
    public class MainScreenCanvas extends GameCanvas implements Runnable {
         private MainMIDlet parent;
         private boolean mTrucking = false;
         Image imgBackgound = null;
         int imgBackgoundX = 0, imgBackgoundY = 0;
         Player player;
         public MainScreenCanvas(MainMIDlet parent)
              super(true);
              this.parent = parent;
              try
                   imgBackgound = Image.createImage("/images/area03_bkg0.png");
                   imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
                   imgBackgoundY = this.getHeight() - imgBackgound.getHeight();
              catch(Exception e)
                   System.out.println(e.getMessage());
          * starts thread
         public void start()
              mTrucking = true;
              Thread t = new Thread(this);
              t.start();
          * stops thread
         public void stop()
              mTrucking = false;
         public void play()
              try
                   InputStream is = getClass().getResourceAsStream("/sounds/scale.mid");
                   player = Manager.createPlayer(is, "audio/midi");
                   player.setLoopCount(-1);
                   player.prefetch();
                   player.start();
              catch(Exception e)
                   System.out.println(e.getMessage());
         public void run()
              Graphics g = getGraphics();
              play();
              while (true)
                   tick();
                   input();
                   render(g);
          * responsible for object movements
         private void tick()
          * response to key input
         private void input()
              int keyStates = getKeyStates();
              if ((keyStates & LEFT_PRESSED) != 0)
                   imgBackgoundX++;
                   if (imgBackgoundX > 0)
                        imgBackgoundX = 0;
              if ((keyStates & RIGHT_PRESSED) != 0)
                   imgBackgoundX--;
                   if (imgBackgoundX < this.getWidth() - imgBackgound.getWidth())
                        imgBackgoundX = this.getWidth() - imgBackgound.getWidth();
          * Responsible for the drawing
          * @param g
         private void render(Graphics g)
              g.drawImage(imgBackgound, imgBackgoundX, imgBackgoundY, Graphics.TOP | Graphics.LEFT);
              this.flushGraphics();
    }

    You can also try to provide a greater Priority to your player thread so that it gains the CPU time when ever it needs it and don't harm the playback.
    However a loop in a Thread and that to an infinite loop is one kind of very bad programming, 'cuz the loop eats up most of your CPU time which in turn adds up more delays of the execution of other tasks (just as in your case it is the playback). By witting codes bit efficiently and planning out the architectural execution flow of the app before start writing the code helps solve these kind of issues.
    You can go through [this simple tutorial|http://oreilly.com/catalog/expjava/excerpt/index.html] about Basics of Java and Threads to know more about threads.
    Regds,
    SD
    N.B. And yes there are more articles and tutorials available but much of them targets the Java SE / EE, but if you want to read them here is [another great one straight from SUN|http://java.sun.com/docs/books/tutorial/essential/concurrency/index.html] .
    Edited by: find_suvro@SDN on 7 Nov, 2008 12:00 PM

  • J2ME problem with threads

    Hi all,
    I would like to ask you for a help. I need to write a small program at my university. I started to write a midlet which function would be to countdown time for sports activities. I woul like to start a new thread - the one that counts down - and at the same time make the main thread sleep. After the "countdown" thread finishes, the main thread wakes up and waits for user input. The problem is that when the "countdown" thread finishes his work, I've got Uncaught exception java/lang/NullPointerException. error and the midlet halts.
    Below you can find the code
    import java.lang.*;
    import java.util.*;
    import javax.microedition.lcdui.*;
    import javax.microedition.midlet.*;
    public class intervals extends MIDlet implements CommandListener
    public Display ekran;
    private SweepCanvas sweeper;
    private Form rundy;
    private TextField round0, round1, round2, round3, round4, round5, round6, round7, round8;
    private long czas,x;
    private Command exitCommand;
    private Command addRound;
    private Command delRound;
    private Command start;
    private TextField repeat;
    private Form odliczanie;
    private Alert ostrz;
    Licznik thread;
    String test;
    StringItem test1;
    int parz,i,j,k;
    static int l;
    int ilrund;
    int ilpowt;
    Item sec;
    long sec1;
    public intervals()
        rundy = new Form("Interwa&#322;y sportowe");
        exitCommand = new Command("Wyj&#347;cie", Command.EXIT, 2);
        addRound = new Command("Dodaj","Dodaj rund&#281;", Command.ITEM,1);
        delRound = new Command("Usu&#324;","Usu&#324; ostatni&#261; rund&#281;", Command.ITEM,1);
        start = new Command("Start", Command.ITEM,1);
        odliczanie = new Form("Odliczanie");
        TextField dodaj(TextField kolej)
            kolej=new TextField("Podaj czas (s) rundy "+parz,null, 4, TextField.NUMERIC);//stworzenie nowej instancji do wybierania czasu trwania rundy
            if(rundy.size()==0)
                rundy.insert(rundy.size(),kolej);
                else
                    rundy.insert(rundy.size()-1, kolej);
            return kolej;
        void odliczanie(TextField round)
            monitor m=new monitor();
            k=Integer.parseInt(round.getString());
            ekran.setCurrent(odliczanie);
            thread=new Licznik(k,odliczanie);
            thread.start();
            ekran.setCurrent(rundy);
    public void startApp()// throws MIDletStateChangeException
        rundy.deleteAll();
        repeat = new TextField("Podaj ilo&#347;&#263; powtórze&#324;",null,1,TextField.NUMERIC);
        rundy.addCommand(addRound);
        rundy.addCommand(exitCommand);
        rundy.setCommandListener(this);
        Canvas obrazek = new MyCanvas();
        ekran = Display.getDisplay(this);
        ekran.setCurrent(obrazek);
        czas=System.currentTimeMillis();
        while (System.currentTimeMillis()<czas+1000)
            continue;
        ekran.setCurrent(rundy);
    public void pauseApp()
    public void destroyApp(boolean unconditional)
        notifyDestroyed();
    public void commandAction(Command c, Displayable s)
        if (c == exitCommand)
            destroyApp(false);
            notifyDestroyed();
        else if(c==addRound)
            if(rundy.size()==0)//Sprawdzenie ilo&#347;ci elementów w celu poprawnego wy&#347;wietlania liczby rund w formie
                parz=1;
                else
                parz=rundy.size();
            switch(parz)
                case 1:
                    round0=dodaj(round0);break;
                case 2:
                    round1=dodaj(round1);break;
                case 3:
                   round2= dodaj(round2);break;
                case 4:
                    round3=dodaj(round3);break;
                case 5:
                    round4=dodaj(round4);break;
                default:
                    ostrz=new Alert("Uwaga","Maksymalna liczba rund wynosi 9", null, AlertType.INFO);
                    ostrz.setTimeout(3000);
                    ekran.setCurrent(ostrz);
            if(rundy.size()==1)
                rundy.append(repeat);
                rundy.addCommand(start);
            rundy.addCommand(delRound);
        else if(c==delRound)
            if(rundy.size()!=0)
                rundy.delete(rundy.size()-2);
                if (rundy.size()==1)
                    rundy.deleteAll();
                if(rundy.size()==0)
                    rundy.removeCommand(delRound);
                    rundy.removeCommand(start);
        else if(c==start)
            ilrund=rundy.size()-1;
            if(this.repeat.size()>0)
                ilpowt=Integer.parseInt(this.repeat.getString());
            ekran = Display.getDisplay(this);
            for (i=1; i<=ilpowt;i++)
                odliczanie= new Form("Odliczanie");
                 for (j=0;j<ilrund;j++)
                    switch(j)
                         case 0:
                             odliczanie(round0);
                             break;
                         case 1:
                             odliczanie(round1);
                             break;
                         case 2:
                             odliczanie(round2);
                             break;
                         case 3:
                             odliczanie(round3);
                             break;
                         case 4:
                             odliczanie(round4);
                             break;
                         case 5:
                             odliczanie(round5);
                             break;
                         case 6:
                             odliczanie(round6);
                             break;
                         case 7:
                             odliczanie(round7);
                             break;
                         case 8:
                             odliczanie(round8);
                             break;
    class Licznik extends Thread
        int czas1,k;
        Form forma;
        monitor m;
        public Licznik(int k,Form formap)
            czas1=k;
            forma=formap;
        public synchronized void run()
            while(czas1>0)
                forma.deleteAll();
                forma.append("Czas pozosta&#322;y (s): "+czas1);
                try{Thread.sleep(1000);} catch(InterruptedException e){e.printStackTrace();}
                czas1--;
            if(czas1<=0)
                m.put();
        }and monitor class
    public class monitor
    boolean busy=false;
    synchronized void get()
        if(!busy)
            try
                wait();
            }catch(InterruptedException e){e.printStackTrace();}
        notify();
    synchronized void put()
        if(busy)
            try
            wait();
            }catch(InterruptedException e){e.printStackTrace();}
        busy=true;
        notify();
    }Can anybody help me with this?

    Groovemaker,
    Your Licznik class has a member m of type monitor, which has not been instantiated (in other words is null) hence, when calling m.put() you get NullPointerException. Please also mind, that using Thread.sleep(1000) is not an accurate way of measuring time.
    If I may, please use recommended for Java class naming conventions - some of your names use lower case, while other don't which is confusing to the reader.
    Daniel

Maybe you are looking for

  • TDS at the time of advance payment(urgent)

    Dear all, I have done the configuration of  TDS at the time of invoice and payment. i checked. it is woking well both at the time of invoice and payment. The issue is when i do the advance payment and when i click the withholding tax tab, it is not g

  • How do i change the title to my photo album:(ios7)

    How do I change the name of the title for one of  my photo albums in ios 7

  • Parameters will it work like Select-Option is there any chance

    Hi Every One I am using Parameters to do selection .but in one case i need to get  some data for the whole month .i have the values in 2 different variables .(If we use select-option then we can use sign,option,low,high .).but how to do here . Any id

  • Jar signing problem? (continue with HOST PJC)

    <1> I've sign jar-file on Oracle9iAS server. <2> First form (with bean from that jar-file) loading asked me for "Granting", and after it runs without problem, bean is worked prefectly. <3> Second form loading shows me nothing, just explorer hanging.

  • MDM with separated ABAP and Java Instance

    We installed SAP ERP system with SRM server and Portal as Java instance. We use Oracle and have 2 oracle schemas/instances: ABAP and Java. After mounting of MDM server and DBMS configuraiton (to Java instance) we have the following oracle objects: Or