Sun C++ std::sort coredump during sorting array of long values

Hello,
I got core dump during execution following test program on both Solaris 9 (compile by CC: Sun C++ 5.5 Patch 113817-19 2006/10/13) and Solaris 10 platforms (compile by CC: Sun C++ 5.9 SunOS_sparc Patch 124863-01 2007/07/25).
Core is dumped during sorting array of about 120k elements of unsigned long types using STL std:sort. The input data is available at link: [file.txt|http://www.savefile.com/files/1924004]
When I change sorting methods to std::stable_sort program works fine.
The funny thing is that when I change order of last two values of input data (swap), sorting is successful with std::sort.
Can anyone tell me if it is Sun C++ compiler bug ?Can I use std::stable_sort method safely?
Below code:
#include <iostream.h>
#include <fstream.h>
#include <set>
#include <string>
int main( int argc, char** argv )
  char readStr[256];
  ifstream file;
  unsigned long *l;
  int i=0;
  l = new unsigned long[119016];
  if (l ==0)
    cout << "Error in allocate memory";
    return -1;
  file.open("file.txt");
  if (!file)
    cout << "Error in openening file";
    return -1;
  while(file.getline(readStr, 256,'\n'))
    cout << readStr<<endl;
    l= atol(readStr);
cout << l[i]<<endl;
i++;
std::sort(l,l+119016); //core dump here!!!
for (i=0;i<119016;i++)
cout <<l[i]<<endl;
file.close();
delete [] l;
return( 0 );
Greetings
Robert                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

You have run into bug 6588033 "std::sort from libCstd loops", which is fixed in current patches.
Get the current patches for Sun Studio and also the current patch for the C++ runtime libraries (SUNWlibC patch).
You can find them here:
[http://developers.sun.com/sunstudio/downloads/patches/index.jsp]
Sun C++ 5.5 probably does not have the fix, since it is quite old and falling out of support.
C++ 5.9 does have the fix.

Similar Messages

  • Sorting Methods for an Array

    I'm trying to sort an object array of bank accounts based on their balance. JGRASP doesn't like my calling statement, which I don't think is correct.
    My question is am I calling the method correctly (trying to set the bankArray[counter].getBalance()) and am I using the sort method correctly?
    my call method
    bankArray = bankArray[counter].selectionSort(bankArray[counter].getBalance(), counter);My sort method:
    public static void selectionSort (double [] sort, int length)
    for (int i = length; i < 1; i--)
    double currentMax;
    int currentMaxIndex;
    currentMax = sort[0];
    currentMaxIndex = 0;
    for (int j = 1; j < i; j++)
    if (currentMax < sort[j])
    currentMax = sort[j];
    currentMaxIndex = j;
    }//End if
    }//End for

    There are some points to notice:
    Point 1: Your method receive an array of double and an int, as you passing a double and an int.
    Point 2: Your algorithm doesn't work properly. First of all, the selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled. Also, note that you don't swap the array elements in any moment.
    Point 3: In Java, your selectionSort method don't need to receive a parameter to inform the array length. The array itself already have that information ("myArray.length").
    Point 4: About the call of your method, you made it as the selectionSort method returns an array of BankAccounts - Supposing that you represent a bank account through an BankAccount class and bankArray[i] is an array of [i]BankAccount objects. It's not true. As you can see, your selectionSort method returns void, or either, returns nothing.
    Observing those 4 first points, we can re-write your selectionSort method like this
         public static void selectionSort(double[] numbers) {
                for (int i = 0; i < numbers.length - 1; i++)
                  int minIndex = i;
                  for (int j = i + 1; j < numbers.length; j++)
                    if (numbers[j] < numbers[minIndex])
                      minIndex = j;
                  double temp = numbers;
              numbers[i] = numbers[minIndex];
              numbers[minIndex] = temp;
    Now, when I try to re-write the call, I noticed other important odd thing about your approach: The [i]selectionSort method was written to sort bankAccounts, but it receives an array of double values. Being thus, you must to previously create a double[] object filled with the accounts' balances and then sort it. But, once sorted, how can you return the balances to their proper account? There is no way to do it. You have to sort a bunch of BankAccount objects, instead of an array of balances...
    An intuitive implementation of this sorting cound be something like that:     public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
    I noticed form your call that the [i]selectionSort method boleng to the BankAccount class. Once this method is static, It's strongly recomended that you invoke this method in a static way (from the class, instead of from an object).
    Here it goes a fictional BankAccount class and a TestBankAccount class. Read it, Run it, Study it, Understand it.
    package help.sun.imbrium;
    public class BankAccount {
         private double balance;
         private int number;
         public static void selectionSort(BankAccount[] accounts) {
              for (int i = 0; i < accounts.length - 1; i++) {
                   int minIndex = i;
                   for (int j = i + 1; j < accounts.length; j++) {
                        double
                             currBalance = accounts[j].getBalance(),
                             minBalance = accounts[minIndex].getBalance()                    
                        if (currBalance < minBalance)
                             minIndex = j;
                   BankAccount temp = accounts;
                   accounts[i] = accounts[minIndex];
                   accounts[minIndex] = temp;
         public BankAccount(int number, double balance) {
              this.balance = balance;
              this.number = number;
         public double getBalance() {
              return balance;
         public void setBalance(double balance) {
              this.balance = balance;
         public int getNumber() {
              return number;
         public void setNumber(int number) {
              this.number = number;
         public String toString(){
              return "[Account #" + number + " balance: $" + balance + "]";
    class TestBankAccount{
         public static void main(String[] args) {
              BankAccount[] accounts = {
                   new BankAccount(1, 154.23),
                   new BankAccount(2, 1554.23),
                   new BankAccount(3, 15.3),
                   new BankAccount(4, 854),
                   new BankAccount(5, -4.79),
              System.out.println("Unsorted:\n\t" + arrayToString(accounts, " "));
              BankAccount.selectionSort(accounts);
              System.out.println("Sorted:\n\t" + arrayToString(accounts, " "));
         private static String arrayToString(Object[] objs, String separator){
              StringBuilder sb = new StringBuilder();
              for (int i = 0; i < objs.length; i++) {
                   Object obj = objs[i];
                   sb.append(obj.toString());
                   if(i < objs.length - 1)
                        sb.append(separator);
              return sb.toString();

  • To hide some headings in top of page during sorting of fields...

    dear experts,
    I have a report in which i am fetching multiple company codes in report and in o/p they are displayed according to company codes, but during sorting of any field in list i want to hide some of the headings in top of page...for any of the radio buttons the headings which i want to hide are...
    1) company code
    2) opening balance and
    3) closing balance
    please help...my code is as follows...
    TYPE-POOLS:slis.
    TABLES:bkpf,bseg,kna1,bsid.
    TYPES:BEGIN OF ty_bsad,
    bukrs TYPE bsad-bukrs,
    gjahr TYPE bsad-gjahr,
    kunnr TYPE bsad-kunnr,
    belnr TYPE bsad-belnr,
    budat TYPE bsad-budat,
    xblnr TYPE bsad-xblnr,
    bldat TYPE bsad-bldat,
    augdt TYPE bsad-augdt,
    dmbtr type bsad-dmbtr,
    END OF ty_bsad.
    TYPES:BEGIN OF ty_kna1,
    kunnr TYPE kna1-kunnr,
    name1 TYPE kna1-name1,
    city  TYPE kna1-ort01,
    END OF ty_kna1.
    TYPES:BEGIN OF ty_knb1,
    kunnr TYPE knb1-kunnr,
    bukrs TYPE knb1-bukrs,
    vzskz TYPE knb1-vzskz,
    END OF ty_knb1.
    TYPES:BEGIN OF ty_bkpf,
    bukrs TYPE bkpf-bukrs,
    gjahr TYPE bkpf-gjahr,
    hwaer TYPE bkpf-hwaer,
    kursf TYPE bkpf-kursf,
    bktxt TYPE bkpf-bktxt,
    belnr TYPE bkpf-belnr,
    budat TYPE bkpf-budat,
    xblnr TYPE bkpf-xblnr,
    bldat TYPE bkpf-bldat,
    waers TYPE bkpf-waers,
    END OF ty_bkpf.
    TYPES:BEGIN OF ty_bsid,
    bukrs TYPE bsid-bukrs,
    gjahr TYPE bsid-gjahr,
    kunnr TYPE bsid-kunnr,
    belnr TYPE bsid-belnr,
    budat TYPE bsid-budat,
    xblnr TYPE bsid-xblnr,
    bldat TYPE bsid-bldat,
    augdt TYPE bsid-augdt,
    dmbtr type bsid-dmbtr,
    END OF ty_bsid.
    TYPES:BEGIN OF ty_bseg,
    bukrs TYPE bseg-bukrs,
    gjahr TYPE bseg-gjahr,
    belnr TYPE bseg-belnr,
    kunnr TYPE bseg-kunnr,
    werks TYPE bseg-werks,
    umskz TYPE bseg-umskz,
    zuonr TYPE bseg-zuonr,
    dmbtr TYPE bseg-dmbtr,
    zbd1t TYPE bseg-zbd1t,
    sgtxt TYPE bseg-sgtxt,
    shkzg TYPE bseg-shkzg,
    zterm TYPE bseg-zterm,
    zfbdt TYPE bseg-zfbdt,
    END OF ty_bseg.
    TYPES:BEGIN OF ty_open,
    bukrs TYPE bsid-bukrs,
    shkzg TYPE bsid-shkzg,
    dmbtr TYPE bsid-dmbtr,
    umskz TYPE bsid-umskz,
    END OF ty_open.
    **Main internal Table
    **For both open & cleared Customer
    DATA:BEGIN OF it_main_all OCCURS 0,
    bukrs TYPE bsad-bukrs,
    gjahr TYPE bsad-gjahr,
    kunnr TYPE bsad-kunnr,
    belnr TYPE bsad-belnr,
    budat TYPE bsad-budat,
    xblnr TYPE bsad-xblnr,
    bldat TYPE bsad-bldat,
    augdt TYPE bsad-augdt,
    dmbtr type bsad-dmbtr,
    hwaer TYPE bkpf-hwaer,
    kursf TYPE bkpf-kursf,
    bktxt TYPE bkpf-bktxt,
    name TYPE kna1-name1,
    city TYPE kna1-ort01,
    vzskz TYPE knb1-vzskz,
    lights TYPE c,
    END OF it_main_all.
    **For Opening balance
    DATA:BEGIN OF it_main_open1 OCCURS 0,
    bukrs TYPE bsid-bukrs,
    opening TYPE p DECIMALS 2,
    END OF it_main_open1.
    **Internal tables
    DATA : t_bsad TYPE STANDARD TABLE OF ty_bsad,
    w_bsad TYPE ty_bsad,
    t_bkpf TYPE STANDARD TABLE OF ty_bkpf,
    w_bkpf TYPE ty_bkpf,
    t_kna1 TYPE STANDARD TABLE OF ty_kna1,
    w_kna1 TYPE ty_kna1,
    t_knb1 TYPE STANDARD TABLE OF ty_knb1,
    w_knb1 TYPE ty_knb1,
    t_bsid TYPE STANDARD TABLE OF ty_bsid,
    w_bsid TYPE ty_bsid,
    t_bseg TYPE STANDARD TABLE OF ty_bseg,
    w_bseg TYPE ty_bseg,
    t_open TYPE STANDARD TABLE OF ty_open,
    w_open TYPE ty_open.
    **ALV display variables
    DATA:fieldcatalog TYPE slis_t_fieldcat_alv WITH HEADER LINE,
    gd_layout TYPE slis_layout_alv,
    gt_events TYPE slis_t_event,
    gt_list_top_of_page TYPE slis_t_listheader,
    heading TYPE slis_t_listheader,
    g_save(1) TYPE c,
    g_exit(1) TYPE c,
    g_variant TYPE disvariant,
    gx_variant TYPE disvariant,
    it_sort TYPE slis_t_sortinfo_alv,
    x_sort TYPE slis_sortinfo_alv.
    **Selection Screens
    SELECTION-SCREEN BEGIN OF BLOCK b1 WITH FRAME TITLE text-001.
    SELECT-OPTIONS:s_bukrs FOR bkpf-bukrs OBLIGATORY,
    s_gjahr FOR bkpf-gjahr OBLIGATORY NO-EXTENSION NO INTERVALS,
    s_kunnr FOR bseg-kunnr OBLIGATORY NO-EXTENSION NO INTERVALS,
    s_name1 FOR kna1-name1 NO-EXTENSION NO INTERVALS,
    s_date FOR bkpf-budat OBLIGATORY,
    s_umskz FOR bsid-umskz.
    SELECTION-SCREEN END OF BLOCK b1.
    SELECTION-SCREEN BEGIN OF BLOCK b3 WITH FRAME TITLE text-003.
    PARAMETERS:xnorm AS CHECKBOX DEFAULT 'X',
    xshbv AS CHECKBOX.
    SELECTION-SCREEN END OF BLOCK b3.
    DATA:golive TYPE d VALUE '20080401',
    date TYPE d,
    date1 TYPE d,
    closing TYPE p DECIMALS 2 VALUE 0,
    opening TYPE p DECIMALS 2 VALUE 0.
    **Start Of Selection
    START-OF-SELECTION.
    PERFORM get_data.
    PERFORM events.
    PERFORM f_layout.
    PERFORM display.
    FORM get_data .
    **Open Customers master data
    SELECT
    bukrs gjahr kunnr belnr budat xblnr bldat augdt dmbtr
    FROM bsid
    INTO TABLE t_bsid
    WHERE bukrs IN s_bukrs
    AND gjahr IN s_gjahr
    AND kunnr IN s_kunnr
    AND budat IN s_date
    AND umskz IN s_umskz.
    **Clear Customers master data
    SELECT
    bukrs gjahr kunnr belnr budat xblnr bldat augdt dmbtr
    FROM bsad
    INTO TABLE t_bsad
    WHERE bukrs IN s_bukrs
    AND gjahr IN s_gjahr
    AND kunnr IN s_kunnr
    AND budat IN s_date
    AND umskz IN s_umskz.
    ****Open Customers data
    IF NOT t_bsid[] IS INITIAL.
    SORT t_bsid BY bukrs bldat.
    SELECT
    bukrs gjahr hwaer kursf bktxt belnr
    FROM bkpf
    INTO CORRESPONDING FIELDS OF TABLE t_bkpf
    FOR ALL ENTRIES IN t_bsid
    WHERE bukrs = t_bsid-bukrs
    AND gjahr = t_bsid-gjahr
    AND belnr = t_bsid-belnr.
    SORT t_bkpf.
    SELECT
    kunnr name1 ort01
    FROM kna1
    INTO TABLE t_kna1
    FOR ALL ENTRIES IN t_bsid
    WHERE kunnr = t_bsid-kunnr
    AND name1 IN s_name1.
    SORT t_kna1.
    SELECT
    kunnr bukrs vzskz
    FROM knb1
    INTO TABLE t_knb1
    FOR ALL ENTRIES IN t_bsid
    WHERE kunnr = t_bsid-kunnr
    AND bukrs = t_bsid-bukrs.
    SORT t_knb1.
    LOOP AT t_bsid INTO w_bsid.
    it_main_all-bukrs = w_bsid-bukrs.
    it_main_all-kunnr = w_bsid-kunnr.
    it_main_all-gjahr = w_bsid-gjahr.
    it_main_all-belnr = w_bsid-belnr.
    it_main_all-budat = w_bsid-budat.
    it_main_all-xblnr = w_bsid-xblnr.
    it_main_all-bldat = w_bsid-bldat.
    READ TABLE t_bkpf INTO w_bkpf WITH KEY bukrs = w_bsid-bukrs gjahr = w_bsid-gjahr belnr = w_bsid-belnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-hwaer = w_bkpf-hwaer.
    it_main_all-kursf = w_bkpf-kursf.
    it_main_all-bktxt = w_bkpf-bktxt.
    ENDIF.
    READ TABLE t_kna1 INTO w_kna1 WITH KEY kunnr = w_bsid-kunnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-name = w_kna1-name1.
    it_main_all-city = w_kna1-city.
    ENDIF.
    READ TABLE t_knb1 INTO w_knb1 WITH KEY kunnr = w_bsid-kunnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-vzskz = w_knb1-vzskz.
    ENDIF.
    it_main_all-lights = '1'.
    APPEND it_main_all.
    CLEAR it_main_all.
    CLEAR : w_bsid, w_bkpf, w_kna1, w_knb1.
    ENDLOOP .
    ENDIF.
    **Clear customers data
    IF NOT t_bsad[] IS INITIAL.
    SORT t_bsad BY bukrs bldat.
    SELECT
    bukrs gjahr hwaer kursf bktxt belnr
    FROM bkpf
    INTO CORRESPONDING FIELDS OF TABLE t_bkpf
    FOR ALL ENTRIES IN t_bsad
    WHERE bukrs = t_bsad-bukrs
    AND gjahr = t_bsad-gjahr
    AND belnr = t_bsad-belnr.
    SORT t_bkpf.
    SELECT
    kunnr name1 ort01
    FROM kna1
    INTO TABLE t_kna1
    FOR ALL ENTRIES IN t_bsad
    WHERE kunnr = t_bsad-kunnr
    AND name1 IN s_name1.
    SORT t_kna1.
    SELECT
    kunnr bukrs vzskz
    FROM knb1
    INTO TABLE t_knb1
    FOR ALL ENTRIES IN t_bsad
    WHERE kunnr = t_bsad-kunnr
    AND bukrs = t_bsad-bukrs.
    SORT t_knb1.
    LOOP AT t_bsad INTO w_bsad.
    it_main_all-bukrs = w_bsad-bukrs.
    it_main_all-gjahr = w_bsad-gjahr.
    it_main_all-kunnr = w_bsad-kunnr.
    it_main_all-belnr = w_bsad-belnr.
    it_main_all-budat = w_bsad-budat.
    it_main_all-xblnr = w_bsad-xblnr.
    it_main_all-bldat = w_bsad-bldat.
    READ TABLE t_bkpf INTO w_bkpf WITH KEY bukrs = w_bsad-bukrs gjahr = w_bsad-gjahr belnr = w_bsad-belnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-hwaer = w_bkpf-hwaer.
    it_main_all-kursf = w_bkpf-kursf.
    it_main_all-bktxt = w_bkpf-bktxt.
    ENDIF.
    READ TABLE t_kna1 INTO w_kna1 WITH KEY kunnr = w_bsad-kunnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-name = w_kna1-name1.
    it_main_all-city = w_kna1-city.
    ENDIF.
    READ TABLE t_knb1 INTO w_knb1 WITH KEY kunnr = w_bsad-kunnr BINARY SEARCH.
    IF sy-subrc EQ 0.
    it_main_all-vzskz = w_knb1-vzskz.
    ENDIF.
    it_main_all-lights = '3'.
    APPEND it_main_all.
    CLEAR : w_bsad, w_bkpf, w_kna1, w_knb1.
    ENDLOOP .
    ENDIF.
    ENDFORM.                    " get_data
    *&      Form  events
    FORM events .
    DATA : l_i_event TYPE slis_alv_event.
    l_i_event-name = 'TOP_OF_PAGE' .
    l_i_event-form = 'TOP2' .
    APPEND l_i_event TO gt_events .
    CLEAR l_i_event .
    ENDFORM.                    " events
    *&      Form  f_layout
    FORM f_layout .
    CLEAR gd_layout.
    gd_layout-detail_popup = 'X'.
    gd_layout-zebra = 'X'.
    gd_layout-no_vline = ' '.
    gd_layout-lights_fieldname = 'LIGHTS'.
    gd_layout-colwidth_optimize = 'X'.
    ENDFORM.                    " f_layout
    *&      Form  display
    FORM display .
    fieldcatalog-fieldname = 'BUKRS'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Company Code'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    fieldcatalog-fieldname = 'GJAHR'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Fiscal year'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    fieldcatalog-fieldname = 'BELNR'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Doc No.'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    fieldcatalog-fieldname = 'BLDAT'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Doc Date'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    fieldcatalog-fieldname = 'BUDAT'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Posting date'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    fieldcatalog-fieldname = 'DMBTR'.
    fieldcatalog-tabname = 'IT_MAIN_ALL'.
    fieldcatalog-seltext_m = 'Amt in local cur.'.
    fieldcatalog-do_sum = 'X'.
    fieldcatalog-just = 'R'.
    APPEND fieldcatalog TO fieldcatalog.
    CLEAR fieldcatalog.
    **For Subtotal of fields
    x_sort-fieldname = 'BUKRS' .
    x_sort-group     = '*'.
    x_sort-subtot    = 'X'.
    APPEND x_sort TO it_sort.
    CLEAR x_sort .
    CALL FUNCTION 'REUSE_ALV_LIST_DISPLAY'
    EXPORTING
    i_callback_program      = sy-repid
    is_layout               = gd_layout
    it_fieldcat             = fieldcatalog[]
    it_sort                 = it_sort
    i_default               = 'X'
    it_events               = gt_events[]
    TABLES
    t_outtab                = it_main_all
    EXCEPTIONS
    program_error           = 1
    OTHERS                  = 2.
    IF sy-subrc <> 0.
    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno
    WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
    ENDIF.
    ENDFORM.
    *&      Form  top_of_page
    FORM top_of_page.
    CALL FUNCTION 'REUSE_ALV_COMMENTARY_WRITE'
    EXPORTING
    i_logo             = 'RUCHI_LOGO'
    it_list_commentary = heading[].
    ENDFORM.
    *&      Form  opening
    FORM opening USING p_bukrs TYPE bsid-bukrs.
    DATA : opdate TYPE d.
    IF s_date-low < golive.
    opening = 0.
    ELSE.
    opdate = s_date-low - 1.
    SELECT
    bukrs shkzg dmbtr umskz
    FROM bsid
    INTO TABLE t_open
    WHERE bukrs IN s_bukrs
    AND kunnr IN s_kunnr
    AND gjahr IN s_gjahr
    AND budat <= opdate.
    LOOP AT t_open INTO w_open.
    IF w_open-shkzg = 'S'.
    opening = opening + w_open-dmbtr.
    ELSEIF w_open-shkzg = 'H'.
    w_open-dmbtr = w_open-dmbtr * ( -1 ).
    opening = opening + w_open-dmbtr .
    ENDIF.
    CLEAR : w_open.
    ENDLOOP.
    SELECT
    bukrs shkzg dmbtr umskz
    FROM bsad
    INTO TABLE t_open
    WHERE bukrs IN s_bukrs
    AND kunnr IN s_kunnr
    AND gjahr IN s_gjahr
    AND budat <= opdate.
    LOOP AT t_open INTO w_open.
    IF w_open-shkzg = 'S'.
    opening = opening + w_open-dmbtr.
    ELSEIF w_open-shkzg = 'H'.
    w_open-dmbtr = w_open-dmbtr * ( -1 ).
    opening = opening + w_open-dmbtr.
    ENDIF.
    CLEAR w_open.
    ENDLOOP.
    ENDIF.
    ENDFORM.
    *&      Form  top2
    FORM top2 .
    date  = s_date-low.
    date1 = s_date-high.
    WRITE : / 'CUSTOMER LEDGER FOR ALL ITEMS' COLOR 7.
    WRITE : / 'Customer Code:', it_main_all-kunnr.
    WRITE : / 'Customer Name:', it_main_all-name.
    WRITE : / 'Customer City:', it_main_all-city.
    ON CHANGE OF it_main_all-bukrs.
    WRITE : / 'Company Code:' COLOR 3 , it_main_all-bukrs COLOR 3.
    PERFORM opening USING it_main_all-bukrs.
    PERFORM closing USING it_main_all-bukrs.
    WRITE : / 'Opening Balance : Rs.' , opening .
    WRITE : / 'Closing Balance : Rs.' , closing .
    ENDON.
    CLEAR : closing, opening.
    IF date1 IS INITIAL.
    WRITE : / 'Date:', date DD/MM/YYYY.
    ELSE.
    WRITE : / 'Date:' , date DD/MM/YYYY, ' to ', date1 DD/MM/YYYY.
    ENDIF.
    ENDFORM.
    *&Form  closing
    FORM closing USING c_bukrs TYPE bsid-bukrs.
    LOOP AT it_main_all WHERE bukrs = c_bukrs.
    closing = closing + it_main_all-dmbtr.
    ENDLOOP .
    closing = closing + opening .
    ENDFORM.
    Edited by: Vishu on Apr 20, 2009 9:32 AM

    it can be done with the help of a system code 'sy-xcode'. it is initialised the time list is sorted so just keeping a check point, we can solve this problem.
    Vishu Khandelwal

  • Sort Second Element in Array of Strict Type Def Clusters

    I need to sort the an array of strict type def clusters by the second or third element in the cluster.  In the past I have used 1-D array sort and sorted by the first element of the cluster.  When I need to sort by the second, third, or fourth element of the cluster I just break down the cluster and rebuild it placing the desired sort element in the first position of the new cluster.  This works for simple tasks and clusters, but as the cluster gets more complicated this becomes a pain to do this.  There must be a cleaner way to sort by other elements within the original array of strict type def clusters.  Has anyone succeeded in doing this a different way?

    Hello,
    Here's the way I would do it...just create a new cluster array, where each cluster contains two elements...the unbundled item you want to sort by, and the cluster itself.  Then sort the new cluster array, then unbundle the sorted cluster array to get the original clusters (now sorted).  Here is a screenshot:
    There may be a better way, but this is the first thing I thought of.
    -D
    Message Edited by Darren on 03-16-200610:00 AM
    Darren Nattinger, CLA
    LabVIEW Artisan and Nugget Penman
    Attachments:
    Sorted_cluster.jpg ‏30 KB

  • How to merge cell during sort in ALV

    Dear all,
    I wrote a ALV report, there is one columns for T001~BUTXT(company code description, data type: char )which has same contents. Using the 'sort', it is unable to merge the same cells, but it works in standard ALV sorting.
    And in the Layout, I don't check the 'without cell merging during sort'.
    Moreover, I also tried to add IT_SORT in the function module 'REUSE_ALV_GRID_DISPLAY', but it didn't work.
    DATA:G_T_SORTCAT TYPE SLIS_T_SORTINFO_ALV,
              G_S_SORT TYPE SLIS_SORTINFO_ALV.
    FORM FRM_DISPLAY_DATA .
       PERFORM FRM_BUILD_FIELDCAT.
       PERFORM FRM_BUILD_SORTCAT.
       PERFORM FRM_BUILD_LAYOUT.
       CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
         EXPORTING
           IT_FIELDCAT   = G_T_FIELDCAT
           I_DEFAULT     = 'X'
           IT_SORT       = G_T_SORTCAT
         TABLES
           T_OUTTAB      = IT_XCFY
         EXCEPTIONS
           PROGRAM_ERROR = 1
           OTHERS        = 2.
       IF SY-SUBRC <> 0.
    * Implement suitable error handling here
       ENDIF.
    ENDFORM. 
    FORM FRM_BUILD_SORTCAT.
       G_S_SORT-FIELDNAME = 'BUTXT'.
       G_S_SORT-UP = 'X'.
       G_S_SORT-SUBTOT = 'X'. 
       G_S_SORT-GROUP = 'UL'.
       APPEND G_S_SORT TO G_T_SORTCAT.
    ENDFORM.  
    So, is there any way to realize cell merging during sort when using ALV function 'REUSE_ALV_GRID_DISPLAY'?
    Thanks and Regards,
    John

    Hi John,
    Set the COMP field of sort to 'X'. You can try as follows:
    FORM FRM_BUILD_SORTCAT.
       G_S_SORT-FIELDNAME = 'BUTXT'.
       G_S_SORT-UP                  = 'X'.
       G_S_SORT-SUBTOT        = 'X'.
       G_S_SORT-GROUP         = 'X'.
        G_S_SORT-COMP            = 'X'.
       APPEND G_S_SORT TO G_T_SORTCAT.
    ENDFORM.
    You can refer to the following link in SCN.
    http://scn.sap.com/thread/3150677
    Regards,
    Abijith

  • What types of sort performed by sort method of Array class ?

    I use normal bubble sort and method Array.sort() to sort some given data of an Array and then count the time.But Array.sort() method takes more time then normal bubble sort.
    Can anybody tell me what types of sort performed by sort method of Array class?

    I'm pretty sure that in eariler versions (1.2, 1.3
    maybe?) List.sort's docs said it used quicksort. Or I
    might be on crack.You are actually both correct, and wrong :)
    From the documentation of the sort methods hasn't changed in 1.2 -> 1.4 (as far as I can notice), and the documentation for sort(Object[]) says (taken from JDK 1.2 docs):
    "This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
    The sorting algorithm is a modified mergesort (in which the merge is omitted if the highest element in the low sublist is less than the lowest element in the high sublist). This algorithm offers guaranteed n*log(n) performance, and can approach linear performance on nearly sorted lists."
    So, how could you be correct? The documentation for e.g. sort(int[]) (and all other primities) says:
    "Sorts the specified array of ints into ascending numerical order. The sorting algorithm is a tuned quicksort, adapted from Jon L. Bentley and M. Douglas McIlroy's "Engineering a Sort Function", Software-Practice and Experience, Vol. 23(11) P. 1249-1265 (November 1993). This algorithm offers n*log(n) performance on many data sets that cause other quicksorts to degrade to quadratic performance."
    Your memory serves you well :)
    /Kaj

  • Sorting a two dimensional array

    Hello!
    I have a twodimensional array that consists of 6 other arrays
    (like array[0 to 5][0 to 4]). The [4] of each sub-array is a index
    number that i'd like to use for sorting the array[0][x] to
    array[5][x] according to their array[x][4]-value. How would I do
    that?
    Thanks!

    use a custom sort function. check the sort() method of the
    array class for sample coding.

  • Sort two one dimensional arrays

    I am having trouble sorting two one dimensional arrays. The first array is int type with ID numbers. I use a bubble sort to sort those. The other array is a string array of video titles. When the first int type array of ID numbers sort, I want the second string type array to follow it. I have tried many things and I can not get it to work properly. Here is what I have for now without the string sort. Can someone help me?
    public class Video
         public static void main(String[] args)
         int[] numID = {168, 397, 102, 39, 239};
         String[] videoTitle = {"Godzilla", "Superman", "Hannibal", "Star Wars", "Men In Black"};
         System.out.println("Here are your selections:");
         System.out.println();
    System.out.print(numID[0]);
         System.out.println("\t" +videoTitle[0]);
         System.out.print(numID[1]);
         System.out.println("\t" +videoTitle[1]);
         System.out.print(numID[2]);
         System.out.println("\t" +videoTitle[2]);
         System.out.print(numID[3]);
         System.out.println("\t" +videoTitle[3]);
         System.out.print(numID[4]);
         System.out.println("\t" +videoTitle[4]);
         System.out.println();
    System.out.println();
    //Sorting ID numbers in ascending order
         int a;
         int b;
         int temp;
    for (a = 0; a < (numID.length - 1); ++a)
         for(b = 0; b < (numID.length - 1); ++b)
              if(numID[b] > numID[b + 1])
                             temp = numID;
                             numID[b] = numID[b + 1];
                             numID[b + 1] = temp;
              System.out.println("Here are your selections in ascending order:");
              System.out.println();
         System.out.print(numID[0]);
              System.out.println("\t" +videoTitle[0]);
              System.out.print(numID[1]);
              System.out.println("\t" +videoTitle[1]);
              System.out.print(numID[2]);
              System.out.println("\t" +videoTitle[2]);
              System.out.print(numID[3]);
              System.out.println("\t" +videoTitle[3]);
              System.out.print(numID[4]);
              System.out.println("\t" +videoTitle[4]);
              System.out.println();
         System.out.println();

    There are ways to do that, of which the simplest would be to switch entries in both arrays at the same time. But since Java is an object-oriented language, the better way to do it would be to make a Video object containing a number and a title, put those objects in an array, and sort the objects.

  • Sorting a 2-D array

    Hello Every one,
                            Can any one please help me out in sorting a 2-D array. Here is the requirement there will be some groups, and each group consists of 'x' number of elements.The user enters only elements but in a zig zag order. And the program short sort out each channel and list out to which group it is belonging (Where the 2-D array of Group name and elements is provided).
    Say for example if there are three groups with some elements in each groups as follows.
    Physics: retarder, force,torque,capacity
    Chemistry: reaction, chemicals, sodium
    Geography: land,map,soil, earth.
    And if the user enters the following input's: soil, torque, chemical, force,reaction, land.
    The program should return the following output:
    Note : The order of the elements should match the order they are defined.
    Physics, force,torque                                    ------------ group name and group elements in the first row
    Chemistry, reaction, chemical                        ------------ group name and group elements in the Second row
    Geography,land, soil                                    ------------ group name and group elements in the third row
    Thanks for the help
    - Raghu
    Solved!
    Go to Solution.

    Sure Jim, I can definitely share my project details.Here is what we are trying to achieve.
    The attached vi is used to transmit the messages to Engine ECM. It takes the input's *.dbc file where the channel names are defined
    The present vi is working like this. It transmit messages correctly only if the messages are defined in the ascending order(the order in which they are defined in the *.dbc file).
    Say for example take 3 PGNS
    1) 18ff0fef Which has the following channels in the PGN
    a) Notch
    b) Gear
    c) Service brake
    2) 14ff2ef which has the following channels in the PGN
    a) Bus_voltage
    b) Bus_current
    c) power
    3)14ff03ef which has the following channels in the PGN
    a) Coolant_temp
    b) oil_press
    c) Imat
    If I want to transmit the following channels and define them in the following order
    1) Gear
    2) Imat
    3) Bus_voltage
    4) Notch
    The program is only writing correct data for Gear,Imat and some garbage values for Bus_voltage and Notch.
    But if I define the channels in the ascending order as defined in the *.dbc file in the following fashion
    1)Notch
    2)Gear
    3)Bus_voltage
    4)Imat
    I can transmit the right data for each channel.
    So what Iam trying to do is Iam planning to sort out all the channels names what user enter's and sort the channels in the  order as defined in the *.dbc file and pass it to the program.
    And the other issue I am facing is if two channels belong to the same PGN like Gear and Notch I have to transmit the values in the same array.
    Say for example i want to transmit the values as follows Notch =4; Gear = 3; Bus_voltage = 25; Imat = 80 the array matrix will be like this
    Array_1: 4,3
    Array_2: 25
    Array_3: 80.
    I was able to sort out all the channels listed in the *.dbc file in to single array but have no clue how to do the rest of work. Can you please help me in achieving the expected result. Iam attaching the vi and picture which describes where channel information and channel values are passed to the program.
    Thank you,
    - Raghu
    Attachments:
    Output.vi ‏27 KB
    TX_GUI.PNG ‏77 KB

  • Sort a 2-dim array?

    Hello!
    Now we have the following problem: We need to sort a 2-dim array depending on the values in the first column. Then we need the corresponding row to move to the right place too... we send a VI so you can see an example of how it might look like. So we need (in this case) the first column to sort so we get 1,2 and 3 and so on, so the last row should be 3,4, 392 and 2047.
    We think this might be easy to solve but we need some tip :-) Thank you and best regards.
    Attachments:
    sortarray.vi ‏17 KB

    I wrote my own 2D string array sort routine. It has come in handy many times. You can enter the column number that you want to sort on, and the entire rows are rearranged in the order of the column sort. If your array is numeric, you can easily change the vi to use numerics instead. One day I hope to make it polymorphic. Here it is:
    - tbob
    Inventor of the WORM Global
    Attachments:
    Sort2DArray(str).vi ‏63 KB

  • How to sort a 2 dim Array ?

    hello
    I would like to sort a 2-dim array of double ( double[][])
    according to the 1st column
    It is possible to sort a 1st dim array (doubel[]) , but the method sort
    of the class Array doesn't work with double[][]).
    I have two (bad) solutions.
    1) Writing a sorting method but I would prefer using the sort' method of java which uses quicksort
    2) Creating a table of objects that implements Comparable but this would decrease performance
    Do you have a better Idea ?
    Thanks a lot

    I would like to sort a 2-dim array of double (double[][]) according to the 1st column
    Which is the first "column"? double[0][x] or
    double[x][0]?
    If it's the second one things get simple: your
    double[][] is really an array of objects where each
    object is an array of doubles. So all you need to do
    is write a custom Comparator for double[] to use the
    sort method:
    compare(Object obj1, Object obj2) {
    double[] d1 = (double[]) obj1;
    double[] d2 = (double[]) obj2;
    return d1[0] > d2[0];
    }Thanks for your so prompt answer.
    I can manage to put the data so that I sort the array according to x as in double[x][0]?
    But WHERE do I have to write the "compare" method ?
    Thanks

  • Better way to sort multi dim int array

    I'm tracking key value pairs of ints. I know that the keys will not repeat. I've decided to do this in an int[][] array
    int[][] data = new int[2][many millions]This app crunches a lot of data so I'm shooting for the best memory handling. I push a bunch of key - value pairs into the array. I will likely populate many if not all data and not have to search until I'm done populating so I'm not sorting as I go.
    I know that I can sort the single dim array data[0] but how can I keep the values array data[1] synchronized? I've tried a few things, all have been successful but I'm wondering if there's a better method. Currently I create copy arrays for the keys and values, sort the original keys, and loop through the copy keys. For each copy key I binary search the sorted keys and drop the value in the correct spot. I don't like having to allocate 2X the amount of memory for the swap arrays. Any thoughts?
    Thanks
    ST

    Jos, thanks for the reply. I tried this method but I don't get as much
    storage since each internal array counts as an object.Yes I know; maybe I've got something for you, waidaminnit <dig-dig/>
    <shuffle-shuffle/> Ah, got it. Suppose you wrap your two dim array in
    a simple class that implements this interface:public interface Sortable {
         public int length();
         public int compare(int i, int j);
         public void swap(int i, int j);
    }I think the semantics of the methods are obvious. Given this interface
    you can sort anything you like using this thingy:public class HeapSort {
         private Sortable s;
         private void heapify(int i, int n) {
              for (int r, l= (i<<1)+1; l < n; i= l, l= (i<<1)+1) {
                   if ((r= l+1) < n && s.compare(l, r) < 0) l= r;
                   if (s.compare(i, l) < 0) s.swap(i, l);
         private void phase1() {
              for (int n= s.length(), i= n/2; i >= 0; i--)
                   heapify(i, n);
         private void phase2() {
              for (int n= s.length(); --n > 0; ) {
                   s.swap(0, n);
                   heapify(0, n);
         public HeapSort(Sortable s) { this.s= s; }
         public Sortable sort() {
              phase1();
              phase2();
              return s;
    }kind regards,
    Jos

  • Simpler way to sort 2-d string array?

    I have a long 2d string array, and I would like to sort by the 2nd value. It originates as:
        public static final String names[][] = {
         {"000000", "Black"},
         {"000080", "Navy Blue"},
         {"0000C8", "Dark Blue"},
         {"0000FF", "Blue"},
            {"000741", "Stratos"},
         {"FFFFF0", "Ivory"},
         {"FFFFFF", "White"}
        };As you can see, they are pre-sorted by the hex values. That is useful for part of the app.
    There are 1,567 entries. I would like to alphabetize the color names and place them in a list widget. I need to keep the associated hex color values with the name values. All I can think of to do something like:
    1) make a temporary long 1-d string array
    2) fill it by loop that appends the hex values to the name values: temp[i] = new String (names[1] + names[i][0])
    3) sort temp[] with built in Java sort
    4) make a permanent new string array, hexValues[] for the hex values
    5) copy the last 6 characters of each item to hexValues[]
    6) truncate the last 6 characters of each item in temp[]
    7) build list widget with temp[]
    Is there a more elegant way? What I'd really like to do is build a 1-d array of int's, with the values representing the alphabetized locations of the names. However, I don't see any built-in which would do that kind of indirect sort.
    Second question -- Can the backgrounds of each item in a list widget be a different color? Ideally the list would show the color name in black or white, and the its color value as background. Specifically, I'm trying to build the list accomplished by the Javascript code here:
    * http://chir.ag/projects/name-that-color/
    and add it to my Java interactive color wheel:
    * http://r0k.us/graphics/SIHwheel.html
    BTW, I have converted his name that color Javascript (ntc.js) to a native Java class. It is freely distributable, and I host it here:
    * http://r0k.us/source/ntc.java
    -- Rich
    Edited by: RichF on Oct 7, 2010 7:04 PM
    Silly forum software; I can't see what made it go italic at the word new.

    I am implementing a sort infrastructure along the lines of camickr's working example, above. Part of my problem is that I am new to both lists and collections. I've tried searching, and I cannot figure out why the compiler doesn't like my "new":
    public class colorName implements Comparable<colorName>
        String     name, hex;
        int          hsi;
        static List<colorName> colorNames;
        public colorName(String name, String hex)
         float     hsb[] = {0f, 0f, 0f};
         int     rgb[] = {0, 0, 0};
         int     h, s, b;     // b for brightness, same as i
         this.name = name;
         this.hex  = hex;
         // Now we need to calculate hsi,
         this.hsi = (h << 10) + (s << 6) + b;  //  hhhhhhssssiiiiii
        ***   findColorName() performs 3 functions.  First, it
        *** will auto-initialize itself if necessary.  Second,
        *** it will perform 3 sorts:
        ***   -3) byHSI:  sort by HSI and return first element of sorted list
        ***   -2) byNAME: sort by name and return first element of list
        ***   -1) byHEX:  (re)reads ntc.names, which is already sorted by HEX;
        ***               returns first element of list
        *** Third, on 0 or greater, will return the nth element of list
        *** Note: ntc.init() need not have been called.
        public colorName findColorName(int which)
         if (which < -3)  which = -3;
         if (which >= ntc.names.length)  which = ntc.names.length - 1;
         if (which == -1)  colorNames = null;     // free up for garbage collection
         if (colorNames == null)
         {   // (re)create list
             colorNames = new ArrayList<colorName>(ntc.names.length);
             for (int i = 0; i < ntc.names.length; i++)
                 colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
            if (which == -1)  return(colorNames.get(0));
    }On compilation, I receive:
    D:\progming\java\ntc>javac colorName.java
    colorName.java:117: cannot find symbol
    symbol  : constructor colorName(java.lang.String[],java.lang.String[])
    location: class colorName
                    colorNames.add(new colorName(ntc.names[1], ntc.names[0]));
                                   ^
    1 errorLine 117 is the second-to-last executable line in code block. I know it is finding the ntc.names[][] array the ntc.class file. I had forgotten to compile ntc.java, and there were other errors, such as in line 115 where it couldn't find ntc.names.length. Compare camickr's two lines:
              List<Person> people = new ArrayList<Person>();
              people.add( new Person("Homer", 38) );As far as I can tell, I'm doing exactly the same thing. If you have any other feedback, feel free to make it. The full source may be found at:
    * http://r0k.us/rock/Junk/colorName.java
    PS1: I know I don't need the parenthesis in my return's. It's an old habit, and they look funny to me without them.
    PS2: My original design had the "static List<colorName> colorNames;" line defined within the findColorName() method. The compiler did not like that; it appears to be that one cannot have static variables within methods. Anyway, that's why I don't have separate sorting and getting methods. I'm learning; "static" does not mean, "keep this baby around". Its meaning is, "there is only one of these babies per class".
    -- Rich

  • How do I open a text file to sort using bubble sort?

    Hi,
    I have a text file, which is a list of #'s.. ex)
    0.001121
    0.313313
    0.001334
    how do you open a text file and read a list? I have the bubble sort code which sorts.. thanks

    I wrote this, but am getting a couple errors:
    import java.util.*;
    import java.io.*;
    public class sort
         public static void main(String[] args)
              String fileName = "numsRandom1024.txt";
              Scanner fromFile = null;
              int index = 0;
              double[] a = new double[1024];Don't use double. You should use something that implements Comparable, like java.lang.Double.
              try
                   fromFile = new Scanner(new File(fileName));
              catch (FileNotFoundException e)
    System.out.println("Error opening the file " +
    " + fileName);
                   System.exit(0);
              while (fromFile.hasNextLine())
                   String line = fromFile.nextLine();
                   a[index] = Double.parseDouble(line);Don't parse to a double, create a java.lang.Double instead.
                   System.out.println(a[index]);
                   index++;
              fromFile.close();
              bubbleSort( a, 0, a.length-1 );No. Don't use a.length-1: from index to a.length-1 all values will be null (if you use Double's). Call it like this:bubbleSort(a, 0, index);
    public static <T extends Comparable<? super T>> void
    d bubbleSort( T[] a, int first, int last )
              for(int counter = 0 ; counter < 1024 ; counter++)
    for(int counter2 = 1 ; counter2 < (1024-counter) ;
    ) ; counter2++)Don't let those counter loop to 1024. The max should be last .
                        if(a[counter2-1] > a[counter2])No. Use the compareTo(...) method:if(a[counter2-1].compareTo(a[counter2]) > 0) {
                             double temp = a[counter2];No, your array contains Comparable's of type T, use that type then:T temp = a[counter2];
    // ...Good luck.

  • Issue with sorting results on the basis of specfic values.

    Hello,
    I written an sql that will sort the results on the basis of values defined in 'IN' clause. I have made use of CASE statement in ORDER BY clause. Its not functioning. My code is:
    SELECT GWLO.productcode,
              GWLA.parentsampletype,
              GWLO.sampletype SampleType,
              max(GWLA.loginid) Loginid,
              max(GWLA.modifiedts) modifiedts
         FROM gwloginattribvars GWL,
              gwloginkeyvals GWLO,
              gwloginkeysadmin GWLA
         WHERE GWLO.productcode = GWLA.productcode
              AND GWLO.sampletype = GWLA.sampletype
              AND GWLO.productcode in ('1002124', 'ABPG', 'ABIG')
              AND GWLO.sampletype <> 'CERTIFICATE-OF-ANALYSIS'
              AND GWLA.parentsampletype IS NOT NULL
         GROUP BY GWLO.productcode, GWLA.parentsampletype, GWLO.sampletype
         ORDER BY
              (CASE GWLO.productcode WHEN '1002124'     THEN 1
                   WHEN 'ABPG'     THEN 2
                   WHEN 'ABIG'     THEN 3
                   ELSE 'LL'
                   END) ASC
    I expected the results to be in sequence what it is defined in CASE - ORDER By clause. This code is givin me error. The error is
    (CASE GWLO.productcode WHEN '1002124' THEN 1
    ERROR at line 16:
    ORA-00907: missing right parenthesis
    Please help. Thanks!

         ORDER BY
              (CASE GWLO.productcode WHEN '1002124'     THEN 1
                   WHEN 'ABPG'     THEN 2
                   WHEN 'ABIG'     THEN 3
                   ELSE 'LL'>                END) ASC
    Can u just explain me in this context? I think it should be another number in the else part - since you are returning numbers in all the 'WHEN' option. Pls explain it.
    Regards.
    Satyaki De.

Maybe you are looking for