C# 如何将步进计数器实现为冒泡排序?
我试图在冒泡排序算法中实现一个步进计数器,但我不知道如何在排序算法的末尾显示计数器。如果有人能解释我该怎么做,那就太好了。多谢各位 我的当前代码:(气泡排序):C# 如何将步进计数器实现为冒泡排序?,c#,sorting,C#,Sorting,我试图在冒泡排序算法中实现一个步进计数器,但我不知道如何在排序算法的末尾显示计数器。如果有人能解释我该怎么做,那就太好了。多谢各位 我的当前代码:(气泡排序): 静态int[]bubbleSort(int[]arr,int n) { int stepCount=0;//有很多方法,但有一种方法是创建一个自定义类来保存所需的两部分信息: public class BubbleObject { public int[] arr { get; set; }
静态int[]bubbleSort(int[]arr,int n)
{
int stepCount=0;//有很多方法,但有一种方法是创建一个自定义类来保存所需的两部分信息:
public class BubbleObject
{
public int[] arr { get; set; }
public int stepCount { get; set; }
}
然后调整必须使用该对象的代码:
static BubbleObject bubbleSort(int[] arr, int n)
{
int stepCount = 0;
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++;
}
}
BubbleObject bo = new BubbleObject() { arr=arr, stepCount=stepCount}
return bo;
}
public static void DisplayArrayBubble(BubbleObject bo)
{
Console.WriteLine("Number of Steps = " + bo.stepCount);
foreach (int i in bo.arr)
{
Console.Write(i.ToString() + " ");
}
}
静态BubbleObject bubbleSort(int[]arr,int n)
{
int-stepCount=0;
对于(int i=0;i
应该可以。还有其他方法。为什么不直接返回int
-步骤数?即
// 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;
}
结果:
Sorted [1, 2, 3, 4, 5, 7] in 6 steps
您可以在return arr;
row之前添加Console.Write(stepCount);
您不需要返回数组,因为您正在对数组进行排序。因此,您可以将返回类型更改为int
并返回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