数组和单链表的排序

//数组的冒泡排序
void sortA2(int a[], int length){

    int i, j, temp;

    for(i = 0; i < length; ++i){

        for(j = length - 1; j > i; --j){

            if(a[j] > a[j - 1]){
                
                temp = a[j];

                a[j] = a[j - 1];

                a[j - 1] = temp;

            }
        }

    }

}

//数组的选择排序
void sortA1(int a[], int length){

    int i, j, temp;

    for(i = 0; i < length; ++i){

        for(j = i + 1; j < length; ++j){

            if(a[j] < a[i]){    //如果后一个元素小于前一个元素则交换

                temp = a[i];

                a[i] = a[j];

                a[j] = temp;

            }

        }
    }

}

//单链表的冒泡排序

void LinkListBubbleSort(LinkNode* head)
{
    if (head == NULL) {
        return;
    }
    LinkNode* cur = head;
    while (cur != NULL) {
        LinkNode* ptr = head;
        while (ptr != cur) {
            if (ptr->data > ptr->next->data) {
                LinkType tmp = ptr->data;
                ptr->data = ptr->next->data;
                ptr->next->data = tmp;
            }
            ptr = ptr->next;
        }
        cur = cur->next;
    }
}

猜你喜欢

转载自blog.csdn.net/hahaha_2017/article/details/81806936