Which of the following code correctly represent jump search?

Which of the following code correctly represent jump search?
A.
Code:
int jumpSearch(int arr[], int x, int n) 
{ 
    int step = n*n; 
    int prev = 0; 
    while (arr[min(step, n)-1] < x) 
    { 
        prev = step; 
        step += sqrt(n); 
        if (prev >= n) 
            return -1; 
    } 
    while (arr[prev] < x) 
    { 
        prev++; 
        if (prev == min(step, n)) 
            return -1; 
    } 
    if (arr[prev] == x) 
        return prev; 
    return -1; 
}
B.
Code:
int jumpSearch(int arr[], int x, int n) 
{ 
    int step = sqrt(n); 
    int prev = 0; 
    while (arr[min(step, n)-1] < x) 
    { 
        prev = step; 
        step += sqrt(n); 
        if (prev >= n) 
            return -1; 
    } 
    while (arr[prev] < x) 
    { 
        prev++; 
        if (prev == min(step, n)) 
            return -1; 
    } 
    if (arr[prev] == x) 
        return prev; 
    return -1; 
}
C.
Code:
int jumpSearch(int arr[], int x, int n) 
{ 
    int step = sqrt(n); 
    int prev = 0; 
    while (arr[min(step, n)-1] < x) 
    { 
        prev = step; 
        step += sqrt(n); 
        if (prev == n) 
            return -1; 
    } 
    while (arr[prev] < x) 
    { 
        prev++; 
        if (prev == min(step, n)) 
            return -1; 
    } 
    if (arr[prev] == x) 
        return prev; 
    return -1; 
}
D.
Code:
int jumpSearch(int arr[], int x, int n) 
{ 
    int step = sqrt(n); 
    int prev = 0; 
    while (arr[min(step, n)-1] < x) 
    { 
        prev = step; 
        step += sqrt(n); 
        if (prev >= n) 
            return -1; 
    } 
    while (arr[prev] > x) 
    { 
        prev++; 
        if (prev == min(step, n)) 
            return -1; 
    } 
    if (arr[prev] == x) 
        return prev; 
    return -1; 
}
 
Answer: b
Explanation: The correct code first makes jumps until an element greater than the required element is found. Then linear search is performed in a backwards direction. If the element is not found then we return -1.
 

Tìm kiếm

Back
Top