简体   繁体   中英

Exchange Memory addresses between array's indixes possible?

I don't have too much experience managing pointers, and other advanced functions but I was thinking if it is possible to make an algorithm to exchange the memory addresses between two elements of an array using pointers, instead copying and moving the value each time ( example while sorting ). Let me explain:

Imagine this array It has 10 elements unsorted, and I pretend to use bubble-sort to sort it (in any order), the typical way is to use a secondary variable to copy the elements and use it as bypass each time i find a smaller or greater number (depends on descending or increasing sorting).

            *----*----*----*----*----*----*----*----*----*----*
array[10] = | 45 | 21 | 32 | 48 | 32 | 22 | 47 | 10 | 11 | 12 |
            *----*----*----*----*----*----*----*----*----*----*
            ^----- Imagine this is 10000

The program realizes that the array[ 1 ] is smaller than the array[ 0 ], so the bubble-sort will exchange their values (this is the typical way) using a secondary variable as bypass.

                   *--------------* 
                   |              ^
                   |              |
            *--------------*--------------*----*----*----*----*----*----*
array[10] = |      45      |      21      | 32 | 22 | 47 | 10 | 11 | 12 |
            *--------------*--------------*----*----*----*----*----*----*
                   |              ^
                   |   *------*   |
                   *-->|BYPASS|---*
                       *------*

So isn't possible to say something like exchange &array[0] and &array[1] addresses? So i avoid the secondary variable? In this case &array[1] = 10000; and &array[0] = 10004.

Thanks for your attention and all suggestions are allowed!

You can do this

 array[0] += array[1];
 array[1] = array[0] - array[1];
 array[0] -= array[1];

and not use a third variable.

An array is a contigious continuous memory space. You cannot eff up it's ordering. It is not a LinkedList, where you would just swap pointers like that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM