用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - c代码库

插补搜寻法查找某值的索引 c算法

2012-11-02 作者: 程序猿style举报

[c]代码库

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 10
#define SWAP(x,y) {int t; t = x; x = y; y = t;}
 
void quicksort ( int[], int, int );
int intsrch ( int[], int );
 
int main ( void )
{
    int number[MAX] = {0};
    int i, find;
 
    srand ( time ( NULL ) );
 
    for ( i = 0; i < MAX; i++ )
    {
        number[i] = rand() % 100;
    }
 
    quicksort ( number, 0, MAX-1 );
 
    printf ( "数列:" );
    for ( i = 0; i < MAX; i++ )
        printf ( "%d ", number[i] );
 
    printf ( "\n输入寻找对象:" );
    scanf ( "%d", &find );
 
    if ( ( i = intsrch ( number, find ) ) >= 0 )
        printf ( "找到数字于索引 %d ", i );
    else
        printf ( "\n找不到指定数" );
 
    printf ( "\n" );
 
    return 0;
}
 
int intsrch ( int number[], int find )
{
    int low, mid, upper;
 
    low = 0;
    upper = MAX - 1;
 
    while ( low <= upper )
    {
        mid = ( upper-low ) *
              ( find-number[low] ) / ( number[upper]-number[low] )
              + low;
        if ( mid < low || mid > upper )
            return -1;
 
        if ( find < number[mid] )
            upper = mid - 1;
        else if ( find > number[mid] )
            low = mid + 1;
        else
            return mid;
    }
 
    return -1;
}
 
void quicksort ( int number[], int left, int right )
{
    int i, j, k, s;
 
    if ( left < right )
    {
        s = number[ ( left+right ) /2];
        i = left - 1;
        j = right + 1;
 
        while ( 1 )
        {
            while ( number[++i] < s ) ;  // 向右找
            while ( number[--j] > s ) ;  // 向左找
            if ( i >= j )
                break;
            SWAP ( number[i], number[j] );
        }
 
        quicksort ( number, left, i-1 );   // 对左边进行递回
        quicksort ( number, j+1, right );  // 对右边进行递回
    }
}


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...