algorithmsortingpuzzle

How do I sort a list of integers using only one additional integer variable?


How to sort list of values using only one variable?


Solution

  • A solution in C:

    #include <stdio.h>
    
    int main()
    {
        int list[]={4,7,2,4,1,10,3};
        int n;  // the one int variable
    
        startsort:
        for (n=0; n< sizeof(list)/sizeof(int)-1; ++n)
            if (list[n] > list[n+1]) {
                list[n] ^= list[n+1];
                list[n+1] ^= list[n];
                list[n] ^= list[n+1];
                goto startsort;
            }
    
        for (n=0; n< sizeof(list)/sizeof(int); ++n)
            printf("%d\n",list[n]);
        return 0;
    }
    

    Output is of course the same as for the Icon program.