Read table and binary search
Hi all,
I have a simple query regarding read int_tab with binary search.
Why reading internal table with binary search fails if it is sorted in descending order table must be sorted in ascending order?
I check fo the algorithm of binary search, it does not talk about sort order. As far as my understanding goes binary search only require sorted table but while reading table in SAP it has to be sorted in ascending order!!
By default binary search assumes that the sort order is ASCENDING.
If you sort the list in descending and then try to binary search your quires will fail. Look at an example:
Let the descending order internal table as:
Field1 Field2
Sam 50000
John 34786
Boob 54321
Alice 12345
When you do binary search with key = 'Sam' then it will directly go to 2nd and 3rd records for comparision. The binary search algorithm compares 'Sam' with 'John' and it concludes that 'Sam' is greater than 'John' and it will continue to look downward into the internal table. And when it reaches the end of the internal table then the value of SY-TABIX = 5 and SY-SUBRC = 8 (Key is greater than the all).
And if you do binary search with key = 'Alice' then the binary search algorithm compares 'Alice' with 'John' and it concludes that 'Alice' is lower than 'John' and it will continue to look upward into the internal table. And when it reaches above the first record in internal table then the value of SY-TABIX = 1 and SY-SUBRC = 4 (points to the next largest entry).
The only correct result you will get is when you execute statement with key='John' (In this particular case) . SY-TABIX = 2 and SY-SUBRC = 0. I think you got this binary search algorithm.
Similar Messages
-
Linear search and binary search
Hi
can any one tell me what is linear and binary search in detail.
and what is the difference between them .
which one is useful in coding.
Thanks&Regards,
S.GangiReddy.hi,
If you read entries from standard tables using a key other than the default key, you can use a binary search instead of the normal linear search. To do this, include the addition BINARY SEARCH in the corresponding READ statements.
READ TABLE <itab> WITH KEY <k1> = <f1>... <kn> = <fn> <result> BINARY SEARCH.
The standard table must be sorted in ascending order by the specified search key. The BINARY SEARCH addition means that you can access an entry in a standard table by its key as quickly as you would be able to in a sorted table.
REPORT demo_int_tables_read_index_bin.
DATA: BEGIN OF line,
col1 TYPE i,
col2 TYPE i,
END OF line.
DATA itab LIKE STANDARD TABLE OF line.
DO 4 TIMES.
line-col1 = sy-index.
line-col2 = sy-index ** 2.
APPEND line TO itab.
ENDDO.
SORT itab BY col2.
READ TABLE itab WITH KEY col2 = 16 INTO line BINARY SEARCH.
WRITE: 'SY-SUBRC =', sy-subrc.
The output is:
SY-SUBRC = 0
The program fills a standard table with a list of square numbers and sorts them into ascending order by field COL2. The READ statement uses a binary search to look for and find the line in the table where COL2 has the value 16.
Linear search use sequential search means each and every reord will be searched to find. so it is slow.
Binary search uses logrim for searching. Itab MUST be sorted on KEY fields fro binary search. so it is very fast.
The search takes place as follows for the individual table types :
standard tables are subject to a linear search. If the addition BINARY SEARCH is specified, the search is binary instead of linear. This considerably reduces the runtime of the search for larger tables (from approximately 100 entries upwards). For the binary search, the table must be sorted by the specified search key in ascending order. Otherwise the search will not find the correct row.
sorted tables are subject to a binary search if the specified search key is or includes a starting field of the table key. Otherwise it is linear. The addition BINARY SEARCH can be specified for sorted tables, but has no effect.
For hashed tables, the hash algorithm is used if the specified search key includes the table key. Otherwise the search is linear. The addition BINARY SEARCH is not permitted for hashed tables.
Binary search must be preffered over linear sarch.
Hope this is helpful, Do reward. -
Reg : Read statement using Binary Search....
I have an Internal Table as below
Value Description
100 Product
2008 Production Year
05 Production Month
I am using Read statement with Binary Search for getting Production Month.
Read table itab with key Description = 'Production Month' binary search.
I am getting sy-subrc as 4 eventhough data is present in the table for Production Month.
What may be the problem.Hi suganya,
use
sort table itab ascending by <production month>.
Read table itab with key description = <production month> binary search.
Remember always, while using binary search always sort the internal table.
Regards,
Sakthi. -
Linear and Binary Searching of Parallel Arrays
I'm an AP student who used the "Fundamentals of Java" by Lambert/Osborne 3rd Edition. This text book has code that doesn't match anything else I've found in other how-to's, guides, or teach yourself books. Not even online can I find code that matches up with the format used in this book!
I've got an assignment that wants me to read in a 4 digit account number of N number of customers, places them in two parallel arrays. Data found in two separate txt files. Create a prompt that ask's for customer's account number then displays account balance. Same program for both linear and binary search methods (2 programs).
I know the search method and how to read the files with a scanner. It is the body of the program that is stumping me. How to call and search the arrays themselves. Any help would be great.First of all, you have posted this question in the wrong place. Please post these kinds of general questions in the New to Java forum.
Second, if you're in an AP class, don't you have a teacher you can ask?
But anyway, here's the idea
For a linear search, you go thru the array element by element, and on each element you call equals(x) to see if that element is equal to what you're searching for (note that primitives use == rather than equals)
For binary search, note first of all that your data MUST BE COMPARABLE (primative or implement the comparable interface) and MUST BE SORTED.
Then what you can do if go to the middle of the list, and if what you are searching for is less than that element, go to the middle of the first half of the list (if it's greater, go the the middle of the upper half of the list) and keep breaking the list in half until you've found the element or you know its not there. -
Adobe reader X and XI search don´t find text like other programs including adobe reader 9? Thanks
You mean, you are trying to search text in a PDF file, and you can do it in Reader 9 but not in later versions of Reader (using the same file)?
-
How to read tables and fields transaction,how to find table from a strucre
hi all,
i am having problem in reading tables and fields for developing a customised report. can anybady help me how to extract tabele and fields from a transaction code and how to map table from a structure.
It will me much help full, if u had any documentation. u should be appreciated.
Thanking u
kiran
Message was edited by:
kiranHi Kiran,
You can make use of the tables or Views available.
Reward If Useful.
Regards,
Chitra -
READ...BINARY SEARCH for more than 1 row.
Hi,
i have an internal table that contains several same entries. now i want to search the table with READ ... BINARY SEARCH ( or in another efficient way ) and get all those entries and not just one/the first one.
how could i do that ? thanks in advance!hi leider,
plz c the below sample code.
loop at i_head into workarea.
READ TABLE i_zvfx_gts008_itm INTO wa_zvfx_gts008_itm
WITH KEY
bukrs = wa_zvfx_gts008_head-bukrs
zzinvoice = wa_zvfx_gts008_head-zzinvoice
BINARY SEARCH.
IF sy-subrc EQ 0.
LOOP AT i_zvfx_gts008_itm INTO wa_zvfx_gts008_itm FROM sy-tabix.
IF ( wa_zvfx_gts008_itm-bukrs NE wa_zvfx_gts008_head-bukrs ) OR
( wa_zvfx_gts008_itm-zzinvoice NE wa_zvfx_gts008_head-zzinvoice ).
EXIT.
ENDIF.
endloop.
this is something like avoiding loop at where condition.
plz reward points if found helpful. -
READ statement with binary search
Hi friends,
I know that while using the READ statement that we have to sort data and use BINARY SEARCH for faster search.
I have a situation
following are internal table contents
belnr agent action
9000001 name1 BRW
9000001 name1 API
when i use READ statement with where condition ( ( belnr - 9000001 ) and ( action = 'BRW' ) ) with binary search then the SY_SUBRC value is 4.
if i remove the binary search then its giving SY-SUBRC value 0.
Can anybody explain why BINARY SEARCH fails.
Points will be rewarded for correct answers.
Thanks and regards,
Murthytry this i am not getting sy-subrc 4
TYPES:BEGIN OF TY_ITAB,
BELNR TYPE BELNR,
AGENT(30),
ACTION(5),
END OF TY_ITAB.
DATA:IT_TAB TYPE TABLE OF TY_ITAB,
WA_TAB TYPE TY_ITAB.
WA_TAB-BELNR = 9000001.
WA_TAB-AGENT = 'name1'.
WA_TAB-ACTION = 'BRW'.
APPEND WA_TAB TO IT_TAB.
CLEAR WA_TAB.
WA_TAB-BELNR = 9000002.
WA_TAB-AGENT = 'name 2'.
WA_TAB-ACTION = 'API'.
APPEND WA_TAB TO IT_TAB.
loop at it_tab into wa_tab.
read table it_tab into wa_tab with key belnr = wa_tab-belnr binary search .
write: sy-subrc, wa_tab-agent.
endloop. -
Arrays,bubblesort, and binary search
Hi I need help I have been working on this homework assignment for the past week and I can't seem to get it so if anyone can help me to figure out what is wrong I would reall grateful. Thanks ahead of time for the help.
Here is what is required for the assignment and also the errors I am getting.
Thanks!
Write a program that sorts an integer array in ascending order and checks whether an integer entered by user is in the array or not. Please follow the following steps to complete the assignment:
1. Declare and create a one-dimensional array consisting of 20 integers.
2. Read 20 integers from the user to initialize the array. Use input dialog box and repetition statement.
3. Build an output string containing the content of the array.
4. Sort the array in ascending order using bubbleSort( ) and swap( ) methods. Then, append the content of the sorted array to the output string.
5. Read an integer search key from the user;
6. Use binarySearch( ) method to check whether the search key is in the array or not. Then, append the search result to the output string.
7. Display the output string in a message box.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
public static void main (String args[])
String input, ouput;
int key;
int index;
int[] array=new int [20];
input=JOptionPane.showInputDialog("Enter 20 Numbers");
for(int counter=0; counter<array.length; counter++)
output+=counter+"\t"+array[counter]+"\n";
array(counter)=Integer.parseInt(input);
JTextArea inputArea=new JTextArea();
outputArea.setText(output);
public void bubblesort(int array2[] )
for(int pass=1; pass<array2.length; pass++){
for(int element=0; element<array2.length-1; element++){
if(array2[element]>array2[element+1])
swap(array2, element, element+1);
public void swap(int array3[], int first, int second)
int hold;
hold=array3[first];
array3[first]=array3[second];
array3[second]=hold;
public void actionPerformed(ActionEvent actionEvent)
String searchKey=actionEvent.getActionCommand();
int element=binarySearch(array, Integer.parseInt(searchKey) );
if(element!=-1)
output.setText("Found value in element " + element);
else
output.setText("Value not found ");
public int binary search(iny array2[], int key)
int low=0;
int high=array2.length-1;
int middle;
while(low<=high){
middle=(low + high)/2;
buildOutput(array2, low, middle, high);
if(key==array[middle] )
return middle;
else if(key<array[middle] )
high=middle-1;
else
low=middle+1
return-1
JOptionPane.showMessageDialog(null, outputArea);
System.exit(0);
} //end main
} //end class
Here is my errors
C:\java>javac SortSearch.java
SortSearch.java:27: illegal start of expression
public void bubblesort(int array2[] )
^
SortSearch.java:20: cannot resolve symbol
symbol : variable output
location: class SortSearch
output+=counter+"\t"+array[counter]+"\n";
^
SortSearch.java:22: cannot resolve symbol
symbol : variable counter
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable output
location: class SortSearch
outputArea.setText(output);
^
SortSearch.java:25: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText(output);
^
5 errorsI am still having problems.
Here is my code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SortSearch {
public static void main (String args[]){
String input, output;
int key;
int index;
int[] array=new int [20];
input=JOptionPane.showInputDialog("Enter 20 Numbers");
for(int counter=0; counter<array.length; counter++)
array(counter)=Integer.parseInt(input);
JTextArea outputArea=new JTextArea();
outputArea.setText(output);
public void bubblesort(int array2[] )
for(int pass=1; pass<array2.length; pass++){
for(int element=0; element<array2.length-1; element++){
if(array2[element]>array2[element+1])
swap(array2, element, element+1);
} //end inner for
} //end outer for
} //end bubblesort
public void swap(int array3[], int first, int second)
int hold;
hold=array3[first];
array3[first]=array3[second];
array3[second]=hold;
} //end swap
public void actionPerformed(ActionEvent actionEvent)
String searchKey=actionEvent.getActionCommand();
int element=binarySearch(array, Integer.parseInt(searchKey) );
if(element!=-1)
outputArea.setText("Found value in element " + element);
else
outputArea.setText("Value not found ");
} //end actionperformed
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
} //end classHere is my errors
C:\java>javac SortSearch.java
SortSearch.java:57: <identifier> expected
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:57: cannot resolve symbol
symbol : class showMessageDialog
location: class javax.swing.JOptionPane
JOptionPane.showMessageDialog(null, outputArea,"Comparisons");
^
SortSearch.java:19: cannot resolve symbol
symbol : method array (int)
location: class SortSearch
array(counter)=Integer.parseInt(input);
^
SortSearch.java:49: cannot resolve symbol
symbol : variable array
location: class SortSearch
int element=binarySearch(array, Integer.parseInt(searchKey) );
^
SortSearch.java:52: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Found value in element " + element);
^
SortSearch.java:54: cannot resolve symbol
symbol : variable outputArea
location: class SortSearch
outputArea.setText("Value not found ");
^
6 errors
Thanks ahead of time I still don't understand the stuff so I sometime don't understand what my errors are telling me so that is why I ask for your help so that maybe it will help make sense. -
Hi EXpert,
I have an internal table say itab and I need to fetch a single record with some given conditions.
Hence I have used READ table statement ,
But on using this read table statement , I am unable to fetch the record :-(((( . It gives sy-subrc = 4.
And the same conditions when are put in Loop at itab statement, then I am able to fetch the data .
My requirement is only 1 record for the given conditions ( in where clause in case of loop at statement).
I think I am probably missing out on some minor thing..
<removed_by_moderator>
Warm Regards,
SUDHA
Edited by: Julius Bussche on Feb 7, 2009 2:48 PMHi,
Test the following Code hope it will solve out your problem,
PARAMETERS: key TYPE i .
TYPES: BEGIN OF t_test,
s_no TYPE i,
name(15),
END OF t_test.
DATA: it_test TYPE STANDARD TABLE OF t_test WITH HEADER LINE.
DO 10 TIMES.
it_test-s_no = sy-index.
it_test-name = 'SDN'.
APPEND it_test TO it_test.
ENDDO.
READ TABLE it_test INTO it_test WITH KEY key.
IF sy-subrc = 0.
WRITE: 'sy-subrc = ' , sy-subrc,
/1 it_test-s_no, 15 it_test-name.
ELSE.
WRITE: 'sy-subrc = ' , sy-subrc,
/ 'Sorry there is no Records with this Key'.
ENDIF.
Kind Regards,
Faisal
Edited by: Faisal Altaf on Feb 7, 2009 6:59 PM -
"Read table" and field symbols
Hello all,
I have a (hopefully simple) question. Let's suppose I want to do the following:
loop at itab1 assigning <fs1>.
read table itab2 assigning <fs2> with table key <fs1>-field1.
if sy-subrc eq 0.
move <fs2>-field1 to ls_out-field1.
endif.
read table itab3 assigning <fs3> with table key <fs1>-field2.
if sy-subrc eq 0.
move <fs3>-field1 to ls_out-field2.
endif.
endloop.
It's also possible to do the following instead:
loop at itab1 assigning <fs1>.
unassign: <fs2>,
<fs3>.
read table itab2 assigning <fs2> with table key <fs1>-field1.
read table itab3 assigning <fs3> with table key <fs1>-field2.
if <fs2> is assigned.
move <fs2>-field1 to ls_out-field1.
endif.
if <fs3> is assigned.
move <fs3>-field1 to ls_out-field2.
endif.
endloop.
My question is: is it "better" to check sy-subrc after each read, and then do a move statement within that if statement, or is it better to check whether the field symbol is assigned each time I want to fill in a field and read everything at the same time?
I'm only really concerned about the case where you don't want to drop out of the loop after the read (so if the read fails you just don't fill any data in). I'm also discounting potential human error (otherwise the sy-subrc method wins hands-down).Just to close this one (albeit somewhat belatedly). I asked Harry Dietz (the ABAP Performance blogging fella) what he would suggest, and he says sy-subrc all the way. Checking that an integer is zero is considerably faster than checking for the assignment, or otherwise, of a field symbol. Furthermore, whilst the field symbol method has the potential to be faster than the sy-subrc method given some compiler optimizations, unfortunately these optimizations don't exist in the ABAP compiler - they're there in the Java compiler though! Shame really. Apparently the ABAP compiler is a pretty simple beast.
Anyway - thanks Harry for clearing this one up! -
How to read tables and fields from a transaction screen.
hi all,
i am having problem in reading fields and tables from a screen, could any one help me in mapping tables from a structure as well.
it will be very help full if u had any documentation.
Thanking u
kiranHi,
In classical debug mode from CALL STACK tab try to find out the structures holding the screen values .
Capture the values from transaction using FIELD SYMBOLS .
See the below code.
DATA : l_prog_val(50) TYPE c VALUE '(SAPLCTMS)WI[]'.
**To get the (SAPLCTMS)WI value in this program from call stack.
FIELD-SYMBOLS: <wi> TYPE ANY.
*Assign the structure (SAPLCTMS)WI to field symbol
ASSIGN (l_prog_val) TO <wi>.
IF sy-subrc NE 0.
EXIT.
*Assign the structure (SAPLCTMS)WI to internal table
ELSE.
it_wi[] = <wi>.
ENDIF.
Sastry. -
Read table and checking condition in PAI
Hi,
I have a requirement where I need to check and compare with (Custom table) Bankn with Partner Bank`s bankn.
I have wrote a code in PAI like this.
MODULE CHECK_BANKN INPUT.
Data: l_bankn like (Custom table)-bankn.
select bankn from (Custom Table) into l_bankn
where recno = g_recno.
IF NOT g_head-bankn IS INITIAL.
Read table i_bvtyp with key bankn = i_bvtyp-bankn .
IF l_bankn <> i_bvtyp-bankn.--------->" Comparison of (custom table) Bankn with internal table I_BVTYP-BANKN
MESSAGE w022 WITH text-w06.
ENDIF.
ENDIF.
ENDMODULE.
My Read Table statement is seems to be wrong and my checking condition is also wrong.
So, how to resolve this?
regards,
KiranHi Kiran,
If you observe your read statement, you are comparing the field with it's own table field.
Read table i_bvtyp with key bankn = i_bvtyp-bankn .
Untill unless you read I_BVTYP, i_bvtyp-bankn will be initial and you cannot find the matching record with Null-Value.
So, I think you need compare with l_bankn.
Read table i_bvtyp with key bankn = i_bankn .
Then you can directly raise a message using SY-SUBRC value.
Read table i_bvtyp with key bankn = i_bankn
if SY-SUBRC <> 0 .
<MESSAGE>
endif.
Regards,
Vijay -
Binary search option with Read statement
Hi,
There are any chances that the Read statement with Binary search option to fail, even though the key exists??
Here the itab is sorted in descending order. and then some duplicates are removed using the delete adjacent statement.
Regards,
Sandhip.Hi,
Here is an example:
sort itab1 by a b c.
loop at itab2 into wa_itab2.
read table itab1 into wa_itab1
with key a = wa_itab2-a
b = wa_itab2-b
c = wa_itab2-c
binary search.
if sy-subrc = 0.
wa_output-a = wa_itab1-a.
endif.
endloop.
Another alternative is to use sorted tables.
Hope it helps...
P.S. Please award points if it helps... -
Can you read Reports and Tables through RFCs and BAPIS?
Is there any way to read established reports and tables through RFC or BAPI function calls? We have a middleware that can execute various BAPIs and RFCs. I see a few promising ones: RFC_READ_REPORT, but no examples anywhere what the parameters needed are for the inputs.
Hello Scott,
Check below FMs for reading tables and programs.
Tables : RFC_READ_TABLE
Program : RFC_READ_DEVELOPMENT_OBJECT
Please note that for reading program using RFC_READ_DEVELOPMENT_OBJECT , lines in program should not exceed 72 chars else FM will throw dump(READ_REPORT_LINE_TOO_LONG).
Program code will appear in table QTAB which is 72 chars wide.
Maybe you are looking for
-
Is it possible to have the calendar "read back" the event created?
You can add an event to your calendar by recording or type in. I want the event to "speak back" "read back" to me what it is at the time chosen on calendar. This would be great for the blind also. I have the alarm app that speaks back the time back
-
All my downloaded photos from iphone as well as vid camera are gone. I was asked a question when trying to put a photo into iphoto and suddenly all events faces, folders were gone. how do i recover them.
-
HT4437 how to mirror ipad air to apple tv
hw does it work
-
9i on Linux --OEM hangs when accessing through the web
I have OMS,Intelligent agent,apache started. Downloaded and installed the JInitiator Plug-in. When I access from NT/2000 I get the Oracle Enterprise Manager Console on my screen and then it hangs. Here is the output from the java console. Oracle JIni
-
SCCM 2012 r2 Deploy USMT Don´t Restore User State
Hi everybody I am migrating my computers from Win Xp to Windows 8.1, with SCCM 2012 R2 with HardLink, my problem is that USMT does not restore the user state on all my computers, it does in some and not in others. the only difenrecia between the te