[转载]排序:长度为n的数组乱序存放着0至n-1. 现在只能进行0与其他数的swap

长度为n的数组乱序存放着0至n-1. 现在只能进行0与其他数的swap 请设计并实现排序。
google笔试小题。题目来源:http://wenku.baidu.com/view/5aa818dda58da0116c17498b.html

休闲小题。
2个key
一个是只能与0 swap,另一个是数组的下标和值是一一对应的。
第二个容易被忽略。所以读到一个元素时,如果值和下标不等,那么可以直接把这个元素的值放到正确位置上去,目标位置的值挪回来。当然这个过程要借助元素0来完成。

假设输入是 2,0,3,1
step 1
遍历数组,找出值为0的元素,和num[0]交换
0 2 3 1

step 2
如果num[1]下标和值匹配,考虑下一个,否则
尝试把num[1]的值借助num[0]放入正确的位置
3 2 0 1 --》  3 0 2 1 --》 0 3 2 1

step 3
重复 step 2,直到 num[1]正确被放置了 1

step 4
num[1]处理完,step2处理下一个元素num[2],直到所有元素的位置和值都匹配

    void swap(int* num, int a, int b){
        if(a == b) return;
        int tmp = num[a];
        num[a] = num[b];
        num[b] = tmp;    
    }

    void sort(int* num, int size){
        int i = 0;
        //move 0 to num[0]
        for(;i<size;i++){
            if(num[i] == 0){
                swap(num, i, 0);
               }
            }
            i = 1;
            while(i<size){
            //postion matched value
              if(num[i] == i){
                 i++;
            }
            //postion mismatch value, then need to place value to the correct postition and continue
            else{
                int tarpos = num[i];
                swap(num, 0, tarpos); // num[tarpos] = 0
                swap(num, tarpos,i); // num[i] = 0
                swap(num, 0, i); // num[0] = 0
            }
        }
    }

    int main(){
        int input[] = {2,0,3,1};
        sort(input, 4);
        int t = 0;
        for(;t<4;t++)
            printf("%d->",input[t]);
        printf("n");
    }

原文地址:http://blog.chinaunix.net/uid-26456800-id-3512430.html

原文地址:https://www.cnblogs.com/shuada/p/3484480.html