p6p
12/29/2015 - 5:48 AM

q1.c

//
//  main.c
//  q1
//
//  Created by master on 2015/12/29.
//  Copyright © 2015年 master. All rights reserved.
//

#include <stdio.h>

typedef int (*compare_cb) (int a, int b);
void bubble_sort(int *number, int count, compare_cb cmp);

int cmp1(int a, int b);
int cmp2(int a, int b);

int main(int argc, const char * argv[]) {
    while (1) {
        printf("Enter the isze of the sequence > ");
        int count;
        scanf("%d", &count);
        int number[100];
        printf("Enter the integer sequence > ");
        for (int i=0; i<count; ++i) {
            scanf("%d", number+i);
        }
        
        printf("The ascending order: ");
        bubble_sort(number, count, cmp1);
        for (int i=0; i<count; ++i) {
            printf("%d ", number[i]);
        }
        
        printf("\nThe descending order: ");
        for (int i=count-1; i>=0; --i) {
            printf("%d ", number[i]);
        }
        
        printf("\nThe custom order: ");
        bubble_sort(number, count, cmp2);
        for (int i=0; i<count; ++i) {
            printf("%d ", number[i]);
        }
        puts("\n");

    }
    return 0;
}

void bubble_sort(int *number, int count, compare_cb cmp) {
    for (int i=0; i<count; ++i) {
        for (int j=0; j<count-1; ++j) {
            if (cmp(number[j], number[j+1])>0) {
                int tmp = number[j+1];
                number[j+1] = number[j];
                number[j] = tmp;
            }
        }
    }
}

int cmp1(int a, int b) {
    return a-b;
}

int cmp2(int a, int b) {
    if (a%2==1 && a%2==0) {
        return 1;
    }
    
    if (a%2==0 && a%2==1) {
        return -1;
    }
    
    if (a%2==0 && b%2==0) {
        return b-a;
    }
    
    if (a%2==1 && b%2==1) {
        return a-b;
    }
    return 0;
}