风萧28

C语言排序

void swap(int *x, int *y){
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}
void insert_sort(int *array, int n){
    int i;
    for (i=1;i<n;i++){
        int tmp = array[i];
        int j = i-1;
        while (j>=0 && tmp < array[j]){
            array[j+1] = array[j];
            j--;
        }
        array[j+1] = tmp;
    }
}
void select_sort(int *array, int n){
    int i,j;
    for(i=0;i<n-1;i++){
        int min_loc = i;
        for (j=i+1;j<n;j++){
            if (array[j] < array[min_loc]){
                min_loc = j;
            }
        }
        if (min_loc != i){
            swap(&array[min_loc],&array[i]);
        }

    }
}

void bubble_sort(int *array, int n){
    int i,j;
    for(i=0;i<n-1;i++){
        int exch_flag = 0;
        for (j=0;j<n-i-1;j++){
            if (array[j]>array[j+1]){
                swap(&array[j],&array[j+1]);
                exch_flag = 1;
            }
        }
        if (!exch_flag){
            break;
        }
    }
}

int _partition(int *array, int left, int right){
    int temp = array[left];
    while (left < right){
        while (left < right && temp < array[right]){
            right--;
        }
        array[left] = array[right];
        while (left < right && temp > array[left]){
            left++;
        }
        array[right] = array[left];
    }
    array[left] = temp;
    return left;
}

void _quick_sort(int *array, int left, int right) {
    if (left < right){
        int mid = _partition(array,left,right);
        _quick_sort(array,left,mid);
        _quick_sort(array,mid+1,right);
    }
}

void quick_sort(int *array, int n){
    int left = 0;
    int right = n-1;
    _quick_sort(array,left,right);
}

 

posted on 2019-06-16 16:45  小流江海  阅读(209)  评论(0编辑  收藏  举报

导航