美文网首页
排序算法之--选择排序

排序算法之--选择排序

作者: WorldPeace_hp | 来源:发表于2018-07-20 17:26 被阅读0次
    原理:
    代码:
    - (void)selectionSort {
        int a[] = {7,1,3,5,8,10,9,2,4,6,19,22,0,33};
        int length = sizeof(a)/sizeof(a[0]);
        
        printfLog(a,length);
        
        int minIndex;
        
        for (int i = 0; i < length - 1; i++) {
            minIndex = i;
            for (int j = i + 1; j < length; j++) {
                if (a[j] < a[minIndex]) {     //寻找最小的数
                    minIndex = j;                 //将最小数的索引保存
                }
            }
            swap(&a[i], &a[minIndex]);
        }
        
        printfLog(a,length);
    }
    
    void swap(int *a, int *b) {
        int temp = *a;
        *a = *b;
        *b = temp;
    }
    
    void printfLog(int a[],int length) {
        for (int i = 0; i < length; i++) {
            printf("%d ",a[i]);
        }
        printf("\n");
    }
    

    相关文章

      网友评论

          本文标题:排序算法之--选择排序

          本文链接:https://www.haomeiwen.com/subject/fglujftx.html