16.4冒泡排序

#include 
#include 
#include 

typedef int ElemType;
typedef struct {
    ElemType *ele;
    int length;
} Table;

void initTable(Table &table, int length) {
    table.ele = (ElemType *) malloc(sizeof(ElemType) * length);
    table.length = length;
    srand(time(NULL));
    for (int i = 0; i < table.length; i++) {
        table.ele[i] = rand() % 100;
    }
}

void printTable(Table table) {
    for (int i = 0; i < table.length; i++) {
        printf("%3d", table.ele[i]);
    }
}

int binarySearch(Table table, int key) {
    int low = 0;
    int hight = table.length - 1;
    int midle;
    while (low <= hight) {
        midle = (hight + low) / 2;
        if (key > table.ele[midle]) {
            low = midle + 1;
        } else if (key < table.ele[midle]) {
            hight = midle - 1;
        } else {
            return midle;
        }
    }
    return -1;
}

void swap(int &a, int &b) {
    int temp;
    temp = a;
    a = b;
    b = temp;
}

void bubbleSort(ElemType *el, int length) {
    bool flag = false;
    for (int i = 0; i < length - 1; i++) {
        for (int j = length - 1; j > i; j--) {
            if (el[j] < el[j - 1]) {
//                swap(el[j], el[j - 1]);
                int temp;
                temp = el[j];
                el[j] = el[j - 1];
                el[j - 1] = temp;
                flag = true;
            }
        }
        if (!flag) {
            return;
        }
    }
};

int main() {
    Table table;
    initTable(table, 10);
    printTable(table);
    printf("\n");
    bubbleSort(table.ele, 10);
    printTable(table);


    return 0;
}

你可能感兴趣的:(考研C,C++数据结构,数据结构)