`

选择和插入排序(c++)

阅读更多
插入与选择排序是两种基础的排序算法,复杂度都为O(n^2);
void selectionSort(int list[], int size) {
    cout<<size<<endl;
    int min;
    int temp;
    for(int i=0; i<size-2; i++) {
        int min = i;
        for(int j=i+1; j<size; j++) {
            if(list[j]<list[min]) min = j;
        }
        if(min!=i) {
            temp = list[i];
            list[i] = list[min];
            list[min] = temp;
        }
    }
}

void insertSort(int list[] , int size) {
    int firstOutOfOrder, location;
    int temp;

    for(firstOutOfOrder=1; firstOutOfOrder<size; firstOutOfOrder++) {
        if(list[firstOutOfOrder]<list[firstOutOfOrder-1]) {
            temp = list[firstOutOfOrder];
            location = firstOutOfOrder;

            do {
                list[location] = list[location-1];
                location--;
            }while(location>0&&list[location-1]>temp);
            list[location] = temp;
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics