小算法合集

本文提供了八种常用算法的实现示例,包括冒泡排序、选择排序、加奇减偶运算、随机数填充数组、求阶乘、判断素数、二分查找等,帮助读者深入理解这些基本算法的工作原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.冒泡排序

/// <summary>
/// 冒泡排序
/// </summary>
/// <param name="a">int型数组</param>
private static void bubbleSort(int[] a)
{
for (int i = 0; i < a.Length - 1; i++)
for (int j = 0; j < a.Length - 1 - i; j++)
{
if (a[j] > a[j + 1])
{
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}

 

2.选择排序

/// <summary>
/// 选择排序
/// </summary>
/// <param name = "myList" ></ param >

private static void selectSort(List<int> myList) {
int temp;
int minIndex;
for (int i = 0; i < myList.Count - 1; i++)
{
minIndex = i;
for (int j = i + 1; j < myList.Count; j++)
{
if (myList[j] < myList[minIndex])
{
minIndex = j;
}
}
if (minIndex != i)
{
temp = myList[minIndex];
myList[minIndex] = myList[i];
myList[i] = temp;
}
}
}

 

3.

4.加奇减偶

/// <summary>
/// 加奇减偶
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private static int printResult(int n)
{
int sum = 0;
for (int i = 1; i <= n; i++)
{
if (i % 2 == 0)
{
sum -= i;
}
else
{
sum += i;
}
}
return sum;
}

 

5.随机数填充数组(均不重复)

/// <summary>
/// 随机数填充数组
/// </summary>
/// <param name="a"></param>
private static void fillArray(int[] a)
{
ArrayList myList = new ArrayList();
Random ran = new Random();
while (myList.Count < a.Length)
{
int num = ran.Next(1, 101);
if (!myList.Contains(num))
{
myList.Add(num);
}
}
for (int i = 0; i < a.Length; i++)
{
a[i] = (int)myList[i];
}
}

 

6.求阶乘

/// <summary>
/// 求阶乘
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private static int factorial(int n)
{
return n == 0 ? 1 : n * factorial(n - 1);
}

 

7.判断素数

/// <summary>
/// 判断一个数是否为素数
/// </summary>
/// <param name="n"></param>
/// <returns></returns>
private static void isPrime(int n)
{
int i;
for (i = 2; i <= Math.Sqrt(n); i++)
{
if (n % i == 0)
{
Console.WriteLine(n + "不是素数");
break;
}
}
if (++i > Math.Sqrt(n))
Console.WriteLine(n + "是素数");
}

 

8.二分查找(数组应是有序的,我这里数组默认是升序的,请注意偶)

/// <summary>
/// 二分查找
/// </summary>
/// <param name="a"></param>
/// <param name="startIndex"></param>
/// <param name="endIndex"></param>
private static int binarySearch(int[] a, int startIndex, int endIndex, int n)
{
if (startIndex > endIndex || a[endIndex] < n || a[startIndex] > n)
{
return 0;
}
int midIndex = (startIndex + endIndex) / 2;
if (n > a[midIndex])
return binarySearch(a, midIndex, endIndex, n);
else if (n < a[midIndex])
return binarySearch(a, startIndex, midIndex, n);
else
return midIndex;
}

转载于:https://www.cnblogs.com/peterpan0707007/p/6599959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值