c# - 如何在冒泡排序中实现计步器?
问题描述
我正在尝试在我的冒泡排序算法中实现一个计步器,但我不知道如何在排序算法结束时显示计数器。如果有人能解释我应该如何去做,那就太好了。谢谢你。
我当前的代码:(冒泡排序):
static int[] bubbleSort(int[] arr, int n)
{
int stepCount = 0; // <- Counter to return and display
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1 - i; j++)
{
if (arr[j + 1] < arr[j])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
stepCount++;
}
}
return arr;
}
public static void DisplayArrayBubble(int[] arr)
{
foreach (int i in arr)
{
Console.Write(i.ToString() + " ");
}
}
解决方案
为什么不直接返回int
- 步数?IE
// arr : will be sorted
// return : number of steps
static int bubbleSort(int[] arr) {
if (null == arr)
return 0;
int stepCount = 0;
for (int i = 0; i < arr.Length - 1; i++)
for (int j = 0; j < arr.Length - 1 - i; j++)
if (arr[j + 1] < arr[j]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
stepCount += 1;
}
return stepCount;
}
演示:
int[] sample = new int[] {1, 5, 4, 3, 2, 7};
int steps = bubbleSort(sample);
Console.WriteLine($"Sorted [{string.Join(", ", sample)}] in {steps} steps");
结果:
Sorted [1, 2, 3, 4, 5, 7] in 6 steps
推荐阅读
- matlab - 初始化函数时出现意外的 MATLAB 运算符错误
- reactjs - 打字稿推断道具不适用于内在元素
- .net - 使用 .Net core 3.1 启动应用程序后立即出现错误“UriFormatException:无效的 URI:无法确定 URI 的格式”
- r - 将闪亮的应用程序共享为网页
- wordpress - 我的网页在手机设备上每行仅显示一行
- functional-programming - 如何将 OCaml cstruct(或 Bigarray)传递给 C?
- javascript - Node.JS - 遍历对象内的数组
- javascript - 在 React 中创建 userInfo 容器
- c# - 使用 System.Drawing 在 C# 中对位图进行高效文本渲染
- flutter - 在 Flutter 中使用 WillPopScope 强制退出应用程序