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

Similar Messages

  • Hi iam using IPHONE4 , when i coonect it to my PC , itunes get hang and don't detect my iphone , how i can sort out this issue plz help me

    Hi iam using IPHONE4 , when i coonect it to my PC , itunes get hang and don't detect my iphone , how i can sort out this issue plz help me

    iPhone, iPad, or iPod touch not appearing in iTunes

  • How we can sort subtotal results value in abap alv report

    Hi, How we can sort subtotal results value in abap alv report

    Thanks a lot for your code
    but i am still getting double and weird results.
    Subtotal     IN     PARTY              KGS        TOTAL VALUE
         1     40008     3,141.20     192,799.00
         1     40008     16,681.06     1,908,659.00
    Subtotal     1          19,822.25     2,101,458.00
         10     40022     4,590.60     531,228.00
         10     40022     3,448.27     377,173.00
    Subtotal     10          8,038.87     908,401.00
         100     40010     270.172     19,852.00
    Subtotal     100          270.172     19,852.00
         101     40036     752.898     61,051.00
         101     40036     207.586     19,431.00
    Subtotal     101          960.484     80,482.00
         102     40048     325.936     32,154.00
         102     40048     264.32     19,364.00
    Subtotal     102          590.256     51,518.00
         103     40066     216.134     18,088.00
    Subtotal     103          216.134     18,088.00
         104     40001     231.96     16,986.00
    Subtotal     104          231.96     16,986.00
         105     40021     585.918     65,461.00
         105     40021     108.683     15,825.00
    Subtotal     105          694.601     81,286.00
         106     40046     209.777     15,341.00
    Subtotal     106          209.777     15,341.00
         107     40043     167.353     14,755.00
    Subtotal     107          167.353     14,755.00
         108     40046     153.023     14,343.00
         108     40046     342.348     32,223.00
    Subtotal     108          495.371     46,566.00
         109     40008     184.085     13,483.00
    Subtotal     109          184.085     13,483.00
         11     40011     5,275.63     524,232.69
         11     40011     6,723.28     643,911.82
    Subtotal     11          11,998.90     1,168,144.51
         110     40067     142.113     13,333.00
         110     40067     492.883     44,428.00
    Subtotal     110          634.996     57,761.00
         111     40040     118.961     13,190.00
         111     40040     492.433     60,029.00
    Subtotal     111          611.394     73,219.00
    Edited by: Timaji Sawant on Feb 16, 2012 12:16 PM
    Edited by: Timaji Sawant on Feb 17, 2012 9:27 AM

  • Using Comparator to sort an array

    I didn't undersatnd why a comparator is used for sorting an arry in ascending order
    For descending also i didn't understand the logic it follows
    I have a program which works for both asc and desc using comparator
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    can anyone explain
    1 why do we are passing an object of Ascend class(code was there in above program) to Arrays.sort() method
    2. what will be retruned by that object
    3 why do we are passing an object of Descend class(code was there in above program) to Arrays.sort() method
    4. what will be retruned by that object
    5 We can sort the array in ascending simply by using Arrays.sort(arr) method directly, then what was usage of Ascend class
    If I am wrong in understating the code of the above pls correct me and tell me the actual usage of Comparator<T> interfance and its method compare()
    Pls....

    camickr wrote:
    Don't forget to use the Code Formatting Tags so the posted code retains its original formatting. That is done by selecting the code and then clicking on the "Code" button above the question input area.am sorry!! pls find the code and try to execute it. It works fine in sorting
    import java.io.*;
    import java.util.*;
         class Ascend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i1.compareTo(i2);
         class Descend implements Comparator<Integer>
              public int compare(Integer i1, Integer i2)
                   return i2.compareTo(i1);
         public class ArrayDemo {
         public static void main(String[] args) throws Exception
              BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
              System.out.println("How many Elements");
              int size = Integer.parseInt(br.readLine());
              Integer[] arr = new Integer[size];
              for(int i=0 ;i<size;i++)
                   System.out.println("Enter "+(i+1)+"th element");
                   arr=Integer.parseInt(br.readLine());     
              Arrays.sort(arr, new Ascend());
              System.out.println("The sorted array in Ascending order is:");
              display(arr);
              Arrays.sort(arr, new Descend());
              System.out.println("The sorted array in Descending order is:");
              display(arr);
         static void display(Integer[] a)
              for(Integer i:a)
                   System.out.print(i+"\t");
                   System.out.println("");
    Can u explain the below
    what happens actually when Arrays.sort(arr,new Descend() ) is executed

  • Can we block negative value posting to final asset

    Dear SAP gurus,
    We are settling the cost from WBSE to AUC & from AUC to Final asset.
    We want to allow the negative postings in AUC. For final asset for time being we want to block the negative posting.
    Can anybody tell me the procedure for disallowing the negative posting in final asset for temporary purpose.
    Thanks & regards,
    Pradip

    You can do this setting at the asset class level in t code OAYZ...drill down on the asset class and uncheck the negative values allowed.
    But this is not recommended for AUC as there isa possibility of credits to the asset.
    if its temporary you can also do it on the asset master by double clicking on the depreciaiton area

  • By using personalization can we default the values as null in oaf

    Hi All,
    Can we change the default values to null....
    Actually i have from and to date fields....when ever page opens the vales are geting defaulting in that fields...
    I need to make this as null....by using personalization is it possible( if yes...need help) or i need to extend the co..
    Regards
    Harry

    Hi Harry,
    If the values are defaulting from the "initial value" property it can be set to null by removing those values from personalization, but I feel it will be defaulting from code if it is so, same can not be achieved by personalization.
    Regards,
    Reetesh Sharma

  • Need help implementing Radix sort to handle negative values

    Hi !
    I'm in desperate need for some help here...
    I've been struggling with this Radix sort algorithm for some time now. It sorts positive integers very well, and very fast, but it cant handle negative values. Is there anyone who can help me improve this algorithm to also sort negative integer values?
    I need it to be as fast or even faster then the current one, and it has to be able to sort values in an array from address x -> y.
    Here's what I have so far
    /** sorts an int array using RadixSort (can only handle positive values [0 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0, bits = 8;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   for (int p = start; p < stop; ++p) {
                        int key = (a[p] & mask) >> rshift;
                        ++cntarray[key];
                   for (int i = 1; i < cntarray.length; ++i)
                        cntarray[i] += cntarray[i-1];
                   for (int p = stop-1; p >= start; --p) {
                        int key = (a[p] & mask) >> rshift;
                        --cntarray[key];
                        b[cntarray[key]+start] = a[p];
                   int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }I think it can be solved by offsetting all positive values the with the number of negative values found in "a" during the last run through the main for loop (as the last (or first) 8 bits in an 32 bit integer contains the prefix bit (first bit in an 32 bit integer), 0 for positive value, 1 for negative).
    Thanks in advance !
    /Sygard.

    ah, beautiful !
    /** sorts an int array using RadixSort (can handle values [-2^31 , 2^31-1])
          * @param a an array to be sorted
          * @param b an array of the same size as a (a.length) to be used for temporary storage
          * @param start start position in a (included)
          * @param stop stop position in a (excluded)
         public void sort(int[] a, int[] b, int start, int stop){
              int[] b_orig = b;
              int rshift = 0;
              for (int mask = ~(-1 << bits); mask != 0; mask <<= bits, rshift += bits) {
                   int[] cntarray = null;
                   try{cntarray = new int[1 << bits];}catch(Exception e){System.out.println("Error");};
                   if(rshift == 24){
                        for (int p = start; p < stop; ++p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = ((a[p] & mask) >>> rshift) ^ 0x80;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
                   else{
                        for (int p = start; p < stop; ++p) {
                             int key = (a[p] & mask) >>> rshift;
                             ++cntarray[key];
                        for (int i = 1; i < cntarray.length; ++i)
                             cntarray[i] += cntarray[i-1];
                        for (int p = stop-1; p >= start; --p) {
                             int key = (a[p] & mask) >>> rshift;
                             --cntarray[key];
                             b[cntarray[key]+start] = a[p];
                        int[] temp = b; b = a; a = temp;
              if (a == b_orig)
                   System.arraycopy(a, start, b, start, stop-start);
         }That's what I ended up with - and it works !
    Thanks a million !!

  • Stacked chart with negative values

    Is it possible to create a stacked verticle bar chart that can display a negative value below the bottom line? Currently, all of my my charts are displaying negative values as if they were positive and the only way to know that the value is negative is to hover over the bar and read the hint.
    Thanks in advance for your help,
    Todd

    Hi Todd,
    Depending how you look at costs, it's not expensive.
    A single developer license of Anychart 5 costs USD 499.00 - 15% if you use the APEX15 promotion code.
    If you spend a couple of days trying to integrate with something else you easily went over that amount.
    So really, it depends in which perspective you look at it. The workaround with Excel, is that really an option? How long would it take for every person wanting to see that screen? How long would it take before you get to $440?
    Anyway if you wait till next year, Anychart 5 is included in APEX 4.0 and you have it out of the box.
    Just my thoughts,
    Dimitri

  • Negative value

    If i declare a variable with type p, is it can store a negative value? Thanks!

    Hi,
    Yes.
    data v_num type p decimals 2 value '-234.00'.
    data v_char(20).
    move v_num to v_char.
    write:/ v_num.
    condense v_char.
    write:/ v_char.
    To put the negative sign before the value use the below function module.
    call function 'CLOI_PUT_SIGN_IN_FRONT'
      changing
        value         = v_char.
    write:/ v_char.
    Message was edited by:
            Velangini Showry Maria Kumar Bandanadham

  • Negative values in Service Entry Sheet

    Hi,
    I am in need of creating service entry sheet lines with negative values (for a certain account assignment).
    Bare with me, this will be long (-;
    In my business scenario, (PS module, Construction Business) I use PO`s for external services with limits only. This PO has only one line ; the vendors are contractors who build for my company various types of buildings.
    Every month I get an invoice from the vendor (contractor) for his monthly work, with a total sum, divided into various types of construction activities (Electricity, Sanitation, Paving and so on).
    Against this invoice, a service entry sheet is created, with service lines from a service model containing construction works, in which I use material groups with account determination, so that each activity has its own GL account and cost element.
    Immediately upon creation of the service entry sheet, logistic invoice verification is made (MIRO) based on the SES, and the payment is transferred to the vendor`s account.
    My problem begins (ah! at last...) with the second monthly invoice and on.
    It is almost by default that in this invoice, some of the construction activities from the previous month appear with negative values - mostly corrections.
    Is there any way I can enter these negative values in a service entry sheet???
    Remember - I cannot revoke the previous entry sheet (because of MIRO and payment)
    I have already encountered error SE397, and the problem is that although the total value is positive, my negative values appear for independent account assignment lines.
    Thanx in Advance,
    Eytan.

    Hi Sanjeev,
    Thank you for your prompt reply.
    I do not need to enter an entirely negative SES.
    As I wrote, only one line is supposed to have a negative value, while the whole document is positive.
    I was able to create a SES with negative values in lines, but only when I used the same material group (hence account assignment). Unfortunately, this does not always help me because In some cases, the negative value belongs to a single account assignment line.
    And why can`t I have a similar (automatic) function like material movement 102?
    SES automatically creates in the background GR document with material movement 101.
    Eytan.

  • How do I print out the value returned by a method in main??

    I'm a total newbie at java, I want to know how I can print out the value returned by this function in the "Main" part of my class:
    public int getTotalPrice(int price)
    int totalprice=price+(price*0.08);
    return totalprice;
    I just want to know how to print out the value for total price under "public static void main(String[] args)". thanks in advance,
    Brad

    Few ways you could do it, one way would be to create an instance of the class and call the method:
    public class Test
        public double getTotalPrice(int price)
            double totalprice = price + (price * 0.08);
            return totalprice;
        public static void main(String[] args)
            Test t = new Test();
            System.out.println(t.getTotalPrice(52));
    }Or another would be to make getTotalPrice() static and you could call it directly from main.

  • Negative values in AIAB, AIBU

    Hi,
    I am tying to post negative values in transactin AIAB & AIBU. System is giving error mesage negative equilance values not allowed. How can I allow negative values.
    The asset on which negative values are posting , have already configured for negative values.
    Help me to resolve the issue.
    Thanks.

    Nitin,
    Goto AS02 -  Asset change - Goto Dep Areas - Double Click on 01 Dep area -  There you can see the Dep Area is in Negative or Positive.
    So for TEMPERORILIY change an do the AIBU/AIAB and make sure to change back once the posting is done.
    Thanks,
    Venkata Raju

  • ICR Upload negative values over Upload File

    Dear Experts (or in most cases Dear Ralph ; ),
    Ich have a question concerning the Upload File which makes it possible in ICR to upload datas via an Excel/TXT Interface.
    My Question is how can I upload negative values?
    Because when I upload  a value like "-100" the value in ICR will be converted to "100", so a positive amount.
    So how can I explain the system that the value in the txt-file should be uploaded as an negative value?
    Should I control it over the debits/credits indicator?
    Or should the minus stand at the back of the values?
    Thanks in advance for any helpful answer
    Regards
    Thomas

    Hi,
    If I am not wrong it will be through debit credit indicator (SHKZG: S for positive and H for negative)
    Regards,
    Saravan Kanuparthy

  • How can i sort out the N lowiest elements from an 1D array faster than using the build in sort function (1D-array) in Labview?

    I need an algorithm that is based on the same sorting-algorithm that Labview uses (or one that is just as fast) but it only needs to sort out the N lowiest elements (and the N-element output array don't need to be sorted).
    /Jonas

    I want all three zeros in the output. You can se the algorithm that I'm looking for as a soft version of Labviews own sort algorithm that only gives you the N (always less then the length of the array) lowiest values as output.If two elements contain the same small value both should be sorted out.
    /Jonas

  • Can values returned by a lookupset be used for interactive sorting or a report filter?

    I have a report that uses multiple stored procedures. I am using the lookupset function to return the values, then I sum the values with custom code, and have them display all into one tablix. However I can not figure out how to use interactive
    sorting or a report filter with values returned by the lookupset function.
    My question is:
    Can you use values returned by a lookupset for interactive sorting or a report filter?
    Thanks!

    Hi WGiff,
    Based on my understanding, you want to perform interactive sorting or filter for the values which come from multiple datasets.
    In Reporting Services, LookupSet()function is used to retrieve a set of values from the specified dataset. So in your scenario, we should use Lookup() function to retrieve values from specified dataset, then perform interactive sorting or filter.
    As we tested in our environment, we retrieve values using Lookup() function form datasets, then sum these values with custom code. After enable interactive sorting or filter for these values, we can get expected results.
    1. Add custom code below in Report Properties.
    Public Shared Value as Integer=0
    Public Shared Function GetValue(Item as Integer) as Integer
    value= value + Item
    return Item
    End Function
    Public Shared Function GetTotal()
    Dim a as integer
    a=value
    value=0
    return a
    End Function
    2. Enable Interactive Sorting.
    3. Add filter within the group.
    If you have any question, please feel free to ask.
    Best regards,
    Qiuyun Yu
    Qiuyun Yu
    TechNet Community Support

Maybe you are looking for

  • Facetime and iMessage Problems on my iPad

    Dear All, I am turning to this community because i have a problem with my iPad and I ran out of ideas how to solve it. Few days ago, I realized that the FaceTime on my iPad  is not working. Every time I try to call someone it says Connection Lost alt

  • Starting BPM process externally.

    Hi, I have created a BPM process and I am able to test it from NWA -> Process repository. But When I am testing from WS Navigator then I am getting an error like-> Web Service returned an error. Fault Code: "(http://schemas.xmlsoap.org/soap/envelope/

  • Managed mail accounts on mobile homes randomly recreating with %@@host...

    Hi I use WGM to setup mail on mobile accounts for our users, but I get this weird issue where a new mail account suddenly is created with %@ourhostname.com. I cant find a pattern to when, and who this happens to. I myself have a Mac Pro, and a laptop

  • HT1386 My new iPhone 5C is not showing up in iTunes

    When I plugged my iPhone into the computer, it doesn't show up on iTunes but will show up in control panel

  • Can I Blur Or Highlight In iMovie HD 6.0.3?

    Is it possible to blur an object in iMovie HD 6.0.3? I have a clip I want to use in a movie I'm putting together but there is someone in the background who doesn't want her face shown in a movie. Is it possible to blur over just her face? Also, is it