using System;
using System.Threading;
using System.Threading.Tasks;

namespace SortVisualizer;

public class BubbleSort : ISortAlgorithm
{
    public string Name => "Bubble Sort";

    public async Task Sort(int[] array, Action refresh, int delay, Action<int> playSound, CancellationToken token)
    {
        for (int i = 0; i < array.Length - 1; i++)
        {
            for (int j = 0; j < array.Length - i - 1; j++)
            {
                if (token.IsCancellationRequested) return;

                playSound(array[j]);
                if (array[j] > array[j + 1])
                {
                    (array[j], array[j + 1]) = (array[j + 1], array[j]);
                    refresh();
                    await Task.Delay(delay);
                }
            }
        }
    }
}
