排序算法的作用非常广泛,可以在计算机程序中得到广泛应用。在实际开发中,我们经常需要对大量的数据进行排序,以便进行快速查找、去重、统计等操作。例如,在实现搜索引擎时,需要对大量的网站和文章进行排序,以便为用户提供准确、高效的搜索结果;在实现数据库时,需要对存储的数据进行排序,以便进行快速查询和数据统计等操作。
// 冒泡排序
int[] BubbleSort(int[] nums)
{
for (int i = 0; i < nums.Length - 1; 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;
}
}
}
return nums;
}
// 创建随机数字数组
int[] RandomNumber(int length)
{
int[] nums = new int[length];
Random random = new Random();
for (int i = 0; i < length; i++)
{
nums[i] = random.Next(0, 10);
}
return nums;
}
void ForeachData(int[] nums)
{
for (int i = 0; i < nums.Length; i++)
{
Console.Write(nums[i] + " ");
}
}
ForeachData(BubbleSort(RandomNumber(10)));