c写的插入排序

逍遥云 posted @ 2011年3月08日 16:03 in c/c++ with tags c 插入排序 , 2153 阅读

本来再想,写这样的初级代码发还是不发,后来还是帖了出来。
 

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static void genIntArray(int *arr, int nlen)
{
    srand((unsigned)time(NULL));
    while(nlen--) *arr++ = rand() % 300 + 5;
}

static void insertion_sort(int *arr, int nlen, int (*sort_func)(int, int))
{
    int i, j, tmp;
    for( i = 1; i < nlen; i++) {
        j = i;
        while( j > 0  && sort_func(arr[j], arr[j - 1])) {
            tmp = arr[j];
            arr[j] = arr[j - 1];
            arr[j - 1] = tmp;
            --j;
        }
    }
}

static int lower_sort(int num1, int num2)
{
    return num1 > num2;
}

static int upper_sort(int num1, int num2)
{
    return num1 < num2;
}

static void printArray(int *arr, int nlen)
{
    printf("[");
    while(--nlen) printf("%d, ", *arr++);
    printf("%d]\n", *arr);
}

int main(void)
{
    int len = 10; 
    int arr[len];
    genIntArray(arr, len);

    printf("before sort:");
    printArray(arr, len);

    insertion_sort(arr, len, lower_sort);
    printf("after lower sort:");
    printArray(arr, len);

    insertion_sort(arr, len, upper_sort);
    printf("after upper sort:");
    printArray(arr, len);
    return 0;
}

后记:在编程中,时常把一个函数当做参数传来传去,这也是编程里面比较有意思的事情。

Avatar_small
Jharkhand Board Mode 说:
2022年9月01日 19:06

Jharkhand Board Model Paper 2023 Class 4 Pdf Download with Answers for English Medium, Hindi Medium, Urdu Medium & Students for Small Answers, Long Answer, Very Long Answer Questions, and Essay Type Questions to Term1 & Term2 Exams at official website. Jharkhand Board Model Paper Class 4 New Exam Scheme or Question Pattern for Sammittive Assignment Exams (SA1 & SA2): Very Long Answer (VLA), Long Answer (LA), Small Answer (SA), Very Small Answer (VSA), Single Answer, Multiple Choice and etc.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter