Day26 算法题-39题:折半查找的递归算法、40题:快速排序

45 阅读1分钟

题目描述:

39题:折半查找的递归算法

40题:快速排序

思路:

折半查找递归实现实质就是将循环变成递归调用,如下代码所示

具体实现:

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

//39题:折半查找的递归算法
//40题:快速排序
#define InitSize 100
typedef int ElemType;
typedef struct{
    ElemType *elem;
    int len;
}SeqList;

void InitList(SeqList &L,int n){//初始化
    L.elem = (ElemType*)malloc(sizeof(ElemType)*InitSize);
    L.len = n;
    srand(time(NULL));
    for (int i = 0; i < n; i++)
    {
        L.elem[i] = rand()%100;//随机初始化0~99之间数值
    }
}

void Print_List(SeqList L)   //打印函数
{
    for (int i = 0;i<L.len;i++)
    {
        printf("%-3d",L.elem[i]);
    }
    printf("\n");
}

//递归实现折半查找
int BinarySearch(ElemType A[],int left,int right,ElemType e)
{
    if (left > right){
        return -1;
    }
    ElemType mid = (left + right) / 2;
    if (A[mid] == e) {          //查找成功直接返回
        return mid;
    }else if (A[mid] < e) {
        return BinarySearch(A, mid + 1, right, e);//查找右半部分
    }else {
        return BinarySearch(A, left, mid - 1, e);    //查找左半部分
    }

}

void swap(ElemType &a,ElemType &b)  //交换值 函数
{
    int val = a;
    a = b;
    b = val;
}

int Partition(ElemType *A,int left,int right)//依分割点排序值
{
    int i,k;
    for(k=i=left;i<right;i++)
        if(A[i] < A[right])
        {
            swap(A[i],A[k]);
            k++;
        }
    swap(A[k],A[right]);    //最后交换k点值和比较值,此时k指向分割点
    return k;
}

void QuickSort(ElemType A[],int low,int high)//快速排序
{
    if(low < high)
    {
        int Pivotops = Partition(A,low,high);
        QuickSort(A,low,Pivotops-1);
        QuickSort(A,Pivotops+1,high);
    }
}

int main() {
    SeqList L;
    InitList(L,10);
    Print_List(L);
    QuickSort(L.elem,0,L.len-1);
    printf("After QuickSort:\n");
    Print_List(L);
    printf("*******************************\n");
    int e;
    printf("The locate of Elem you want\n");
    scanf("%d",&e);
    int i = BinarySearch(L.elem,0,L.len-1,e);
    if(i == -1){
        printf("Search is not successful\n");}
    else{
        printf("Locate is %d\n",i+1);
    printf("*******************************\n");}
    return 0;
}

输出结果:

1:

11111111.png

2:

2222222222222.png

3:(未找到)

33333333333333.png

小结:

我是按照题目顺序先写的折半查找,可是搞了半天发现每次都查找失败,后来我突然醒悟,我的数组都不有序,我折半折个毛啊,后来改成先排序后查找就好了,我可真是,,,,服了

04CC657B.png