基础排序算法(冒泡排序、选择排序、插入排序)

来源:互联网 发布:创力cms 编辑:程序博客网 时间:2024/05/16 15:46

冒泡排序、选择排序、插入排序

#include <stdio.h>
#include <string.h>

int strsrc[10] = {10, 1, 2, 5, 3, 9, 11, 12, 20, 9};
int str[10];

void load_str(void)
{
    int len = sizeof(str);
    memcpy(str, strsrc, len);
}

void swap(int* x, int* y)
{
    int temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

void exch(int* x, int* y)
{

    if(*x > *y) swap(x, y);
}

void sort_print(void)
{
    int i;
    int len = sizeof(str) / 4;

    for(i = 0;i <len; i++) printf("%d ", str[i]);
    printf("/n");
}

void sort_bubble(void)
{
    int i, j, l;
    l = sizeof(str) / 4;

    for(i = 0; i < l; i++)
    {
        for(j = l - 1; j > i; j--)
        {
            exch(&str[i], &str[j]);
        }
    }
}

void sort_select(void)
{
    int i, j, l;
    int min;
    int index = 0;

    l = sizeof(str) / 4;

    for(i = 0; i < l; i++)
    {
        min = str[i];
        for(j = i + 1; j < l; j++)
        {
            if(str[j] < min)
            {
                min = str[j];
                index = j;
            }
            
        }
        swap(&str[i], &str[index]);
    }
}

void sort_insert(void)
{
    int i, j, l;

    l = sizeof(str) / 4;

    for(i = 1; i < l; i++)
    {
        for(j = 0; j < i; j++)
        {
            if(str[i] < str[j])
            {
                swap(&str[i], &str[j]);
            }
            
        }

    }
}


int main()
{
    printf("------------------------------sort_bubble------------------------------/n");
    load_str();
    sort_print();
    sort_bubble();
    sort_print();
    printf("------------------------------sort_select------------------------------/n");
    load_str();
    sort_print();
    sort_select();
    sort_print();
    printf("------------------------------sort_insert------------------------------/n");
    load_str();
    sort_print();
    sort_select();
    sort_print();

    return 0;
}

原创粉丝点击