[ABAP] How do I implement basic sorting algorithms (e.g., bubble sort, insertion sort) in ABAP?
To implement basic sorting algorithms like bubble sort and insertion sort in ABAP, you can follow the steps below:
-
Create an ABAP program using the ABAP editor (SE38 transaction).
-
Define an internal table to hold the elements you want to sort. For example:
1DATA: lt_data TYPE TABLE OF i.
- Populate the internal table with the data you want to sort. For example:
1APPEND 10 TO lt_data.
2APPEND 5 TO lt_data.
3APPEND 8 TO lt_data.
- Implement the desired sorting algorithm. Here are the steps for bubble sort:
1DATA: lv_swapped TYPE abap_bool.
2
3DO.
4 lv_swapped = abap_false.
5
6 LOOP AT lt_data INTO DATA(ls_data) FROM 1 TO lines(lt_data) - 1.
7 IF ls_data > lt_data[ sy-tabix ].
8 SWITCH lt_data[ sy-tabix ] WITH ls_data.
9 lv_swapped = abap_true.
10 ENDIF.
11 ENDLOOP.
12
13 IF lv_swapped = abap_false.
14 EXIT. " All elements are in order, exit loop
15 ENDIF.
16ENDDO.
- After the sorting algorithm finishes, you can display the sorted elements. For example:
1LOOP AT lt_data INTO DATA(ls_data).
2 WRITE: / ls_data.
3ENDLOOP.
Here is a complete example of an ABAP program that sorts elements using bubble sort:
1REPORT z_sorting_algorithm.
2
3DATA: lt_data TYPE TABLE OF i.
4APPEND 10 TO lt_data.
5APPEND 5 TO lt_data.
6APPEND 8 TO lt_data.
7
8DATA: lv_swapped TYPE abap_bool.
9
10DO.
11 lv_swapped = abap_false.
12
13 LOOP AT lt_data INTO DATA(ls_data) FROM 1 TO lines(lt_data) - 1.
14 IF ls_data > lt_data[ sy-tabix ].
15 SWITCH lt_data[ sy-tabix ] WITH ls_data.
16 lv_swapped = abap_true.
17 ENDIF.
18 ENDLOOP.
19
20 IF lv_swapped = abap_false.
21 EXIT. " All elements are in order, exit loop
22 ENDIF.
23ENDDO.
24
25LOOP AT lt_data INTO DATA(ls_data).
26 WRITE: / ls_data.
27ENDLOOP.
You can modify this example to implement other sorting algorithms like insertion sort by changing the inner loop conditions and element swapping logic accordingly.