-
寻找变化(二分法)
输入:int[] nums={0,0,0,1,1,1,1,1};
寻找1第一次出现的位置
public void ClassMain(){
int left=0;//左指针
int right=nums.Length-1;//右指针
while(left<right){//如果左指针>=右指针
int index=left+(right-left)/2;//定位的位置***
if(nums[index]==1){
right=index;
}else{
left=index+1;//***
}
}
//指针寻找的始终是1,当左指针从0变1时,结束
Console.WriteLine(left);
} -
二分法查找与暴力查找。给出暴力查找法编写一个程序BruteForceSearch,在你的计算机上比较它和
BinarySearch处理largeW.txt和largeT.txt所需的时间。
class Sequence
{
public void SequenceMain()
{
int[] nums = new int[100];
for(int i = 0; i < nums.Length; i++)
{
Random ran = new Random();
nums[i] = ran.Next(1, 100);
}
Console.WriteLine(“请输入需要查找的数:”);
int find = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < nums.Length; i++)
{
for (int j = 0; j < nums.Length - i-1; j++)
{
if (nums[j] > nums[j + 1])
{
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
}
}
}
int left = 0;
int right = nums.Length - 1;
//bool result= BinarySearch(nums, find,left,right);
bool result = ViolSearch(nums, find);
for (int i = 0; i < nums.Length; i++)
{
Console.Write(nums[i] + “,”);
}
Console.WriteLine();
Console.WriteLine(result);} //二分法 private bool BinarySearch(int[] nums, int find,int left,int right) { bool result = false; while (left < right) { int mid = left + (right - left) / 2; if (nums[mid] > find) { right = mid; BinarySearch(nums, find, left, right); } else if (nums[mid] < find) { left = mid + 1; BinarySearch(nums, find, left, right); } else { result = true; break; } } return result; } //暴力查找法 private bool ViolSearch(int[] nums, int find) { bool result = false; for(int i=0;i< nums.Length; i++) { if(nums[i]== find) { result = true; break; } if (nums[i] > find) { break; } } return result; }
}
二分法查找与暴力查找。(C#)
最新推荐文章于 2024-08-19 16:20:52 发布