顺序表的冒泡排序算法及二分法查找代码实现

本文主要实现了比较经典的冒泡排序算法(对已经有序或者基本有序的顺序表复杂度大大降低),和二分法查找,各位看官看代码吧

//冒泡排序算法及二分法查找
#include "stdio.h"
typedef struct {
    int key;
}SSTable_Elem_Type;
typedef struct {
    SSTable_Elem_Type*elem;
    int length;
}SSTable_Typedef;
void Bubble_Sort(SSTable_Typedef*ST)
{
    unsigned char i = 0, j = 0;
    unsigned char finish_flag = 0;//0:完成排序的
    SSTable_Elem_Type tmp;
    for (i = 0; i < ST->length; i++)
    {
        finish_flag = 1;//假设完成了排序
        for (j = 0; j < ST->length - i - 1; j++)
        {
            if (ST->elem[j].key>ST->elem[j + 1].key)
            {
                finish_flag = 0;
                //交换数据
                tmp = ST->elem[j];//每次都取最大的
                ST->elem[j] = ST->elem[j + 1];
                ST->elem[j + 1] = tmp;
            }
        }
        if (finish_flag == 1)//一趟冒泡排序没有发生交换,说明已经有序已经完成排序
            break;
        printf("sorting\r\n ");
    }
}
//初始化顺序表
void Init_SSTable(SSTable_Typedef* SSTable, SSTable_Elem_Type*buf, int len)
{
    SSTable->elem = buf;
    SSTable->length = len;
}
//折半查找
//buf 已经排序
int bisearch(SSTable_Typedef* SSTable,int search_data)
{
    int low = 0;
    int high=SSTable->length-1;
    int mid;
    while (low <= high)
    {
        mid = (low + high) / 2;
        if (search_data == SSTable->elem[mid].key) return (mid+1);
        else if (search_data < SSTable->elem[mid].key) high = mid - 1;
        else low = mid + 1;
    }
    return 0;
}
#define len 5
int main(void)
{
    SSTable_Typedef ST;
    SSTable_Elem_Type ST_Elem[10];

    int i = 0;
    Init_SSTable(&ST, ST_Elem, 10);
    for (i = 0; i < 10; i++)
    {
        ST_Elem[i].key = 10-i;
    }
    printf("unsorted:");
    for (i = 0; i < 10; i++)
    {
        printf("%d ", ST.elem[i].key);
    }
    Bubble_Sort(&ST);
    printf("\r\nsorted:");
    for (i = 0; i < 10; i++)
    {
        printf("%d ", ST.elem[i].key);
    }
    printf("%d",bisearch(&ST, -11) );
    printf("\r\n");
    while (1);
    return 0;
}

结果:
顺序表的冒泡排序算法及二分法查找代码实现_第1张图片

你可能感兴趣的:(算法,冒泡排序,顺序表的二分法查找)