C語言使用stdlib.h庫函數的二分尋找和快速排序程式

來源:互聯網
上載者:User

快速排序:

#include <stdlib.h>#include <stdio.h>#include <string.h>#define LENGTH(x) sizeof(x)/sizeof(x[0])/**輸出數組元素*\param arr:指向數組的指標*\param len:數組元素的個數*/void print(char (*arr)[10],int len){    int i;    for (i=0;i<len;i++)    {        printf("%s ",arr[i]);    }    printf("\n");}int main(){    char arr[][10]={"bac","bca","abc","acb","cba","cab"}; /* 定義二維字元數組*/    char *key="bca";/* 要尋找的字串*/    char *ptr=NULL; /* 字元指標*/// 輸出未排序時字元數組的內容    printf("before qsort :");    print(arr,LENGTH(arr));    /* 使用qsort對字元數組排序*/    qsort((void *)arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);    /* 輸出排序後字元數組的內容*/    printf("after qsort :");    print(arr,LENGTH(arr));    /* 採用二分尋找尋找指定字元*/    ptr=(char *)bsearch(key,arr,LENGTH(arr),sizeof(arr[0]),(int (*)(const void *,const void *))strcmp);    if(ptr)    {        /* 找到*/        printf("%s is in the array\n",key);    }    else/* 沒找到*/    {        printf("%s isn't in the array\n",key);    }    return 0;}

二分尋找:

#include<stdlib.h>#include<stdio.h>#define ArrayLen(arr) (sizeof(arr) / sizeof(arr[0]))int numarray[] = {123, 145, 512, 627, 800, 933};int numeric (const int *p1, const int *p2){    return(*p1 - *p2);}int* lookup(int key){//傳回值是指向key的地址     int *itemptr;    // The cast of (int(*)(const void *,const void*)) is needed to avoid a type mismatch error at// compile time    itemptr = (int *)bsearch(&key, numarray, ArrayLen(numarray),\                             sizeof(int), (int(*)(const void *,const void *))numeric);    return (itemptr);}int main(void){int *p = lookup(512);if(NULL != p)printf("找到的key是%d,", *p);printf("key的下標是%d\n", (p - numarray));    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.