Parity exchange sort for equal values

輸入法忘記如何調回簡體了,

奇偶交換排序排序

貌似有點n為奇數與偶數的細節問題,再想想;


#include 


float a[8] = { 1.4062,  2.6065,  1.2786,  0.3698,  1.4062,  2.6065,  1.2786,  0.3698 };
void swap(float& x, float& y);
void sort(float* A, int n);

void print_vector(float* A, int n) {
    for (int i = 0; i < n; i++) {
        printf("%7.4f  ", A[i]);
    }
    printf("\n");
}

int main() {
    float a[8] = { 1.4062,  2.6065,  1.2786,  0.3698,  1.4062,  2.6065,  1.2786,  0.3698 };
    int n = 8;

    printf("");
    print_vector(a, n);
    sort(a, n);
    print_vector(a, n);
    

    return 0;
}


void swap(float &x, float &y) 
{
    float tmp;

    tmp = x;
    x = y;
    y = tmp;
}


void sort(float *A, int n){
    int  arrayLength = n;
    bool oddSorted   = false;//if false, then, 奇數次,依然有的排
    bool evenSorted  = false;//if false, then, 偶數次,依然有的排

    while (!oddSorted || !evenSorted){
        int base = 0;
        oddSorted = true;
        evenSorted = true;

        for (int i = base; i < arrayLength - 1; i += 2) {
            if (A[i] > A[i + 1]) {
                swap(A[i],A[i + 1]);
                oddSorted = false;
            }
        }

        base = 1;
        for (int i = base; i < arrayLength - 1; i += 2) {
            if (A[i] > A[i + 1]) {
                swap(A[i], A[i + 1]);
                evenSorted = false;
            }
        }
    }
}

你可能感兴趣的:(排序)