首页 > 解决方案 > 如何在冒泡排序中实现计步器?

问题描述

我正在尝试在我的冒泡排序算法中实现一个计步器,但我不知道如何在排序算法结束时显示计数器如果有人能解释我应该如何去做,那就太好了。谢谢你。

我当前的代码:(冒泡排序):

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() + "  ");
    }
}

标签: c#sorting

解决方案


为什么不直接返回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

推荐阅读