【发布时间】:2019-04-26 05:01:02
【问题描述】:
目前,我有一个实现插入排序的程序,然后使用二进制搜索来搜索它(一个整数数组)。我目前似乎有一个 1 off 错误。
我的插入排序应该按降序排序。现在,似乎存储在最后一个位置的值丢失了。
#include <stdio.h>
void insertionSort(int nums[], int size)
{
int i, key, j;
for (i = 1; i < size; i++)
{
key = nums[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && nums[j] > key)
{
nums[j + 1] = nums[j];
j = j - 1;
}
nums[j + 1] = key;
}
}
int binarySearch(int nums[], int size, int searchVal)
{
int l = 0, r = size - 1;
while (l <= r)
{
int m = l + (r - l) / 2;
// Check if x is present at mid
if (nums[m] == searchVal)
return m;
// If x greater, ignore left half
if (nums[m] < searchVal)
l = m + 1;
// If x is smaller, ignore right half
else
r = m - 1;
}
// if we reach here, then element was
// not present
return -1;
}
int main()
{
int n;
printf("Enter the number of elements (between 1 and 50) in the array: \n");
scanf("%d", &n);
int i, nums[n];
printf("Enter %d positive integers: \n", n);
for (i = 0; i < n; i++)
{
scanf("%d", &nums[i]);
}
int x = 0;
insertionSort(nums, n);
printf("Enter a positive integer or -1 to quit: \n");
scanf("%d", &x);
do
{
int ind = binarySearch(nums, n, x);
if (ind > 0)
{
printf("Found\n");
}
else
{
printf("Not Found\n");
}
printf("Enter a positive integer or -1 to quit: \n");
scanf("%d", &x);
} while (x != -1);
return 0;
}
结果:
Enter the number of elements (between 1 and 50) in the array:
9
Enter 9 positive integers:
7
4
10
49
6
12
32
17
Enter a positive integer or -1 to quit:
4
Not Found
Enter an positive integer -1 or to quit
12
Found
Enter a positive integer or -1 to quit:
5
Not Found
Enter a positive integer or -1 to quit:
49
Found
Enter a positive integer or -1 to quit:
-1
您可以看到一切正常,但我测试数字 4 的第一个测试。有谁知道我为什么落后 1?
【问题讨论】:
-
见how to debug small programs。这里的第一步是将排序部分和搜索部分分开,并验证问题是否在您认为的位置。
-
“输入9个正整数”,给定8个?
-
if (ind > 0)应该是if (ind >= 0)。 -
return m;和if (ind > 0)将永远找不到索引0处的元素...
标签: c binary-search insertion-sort