Search code examples
algorithmsortingbreakbubble-sort

How can I perform only one swap on button press?


async bubbleSort(values, size) {
    sort_button = true;
    for(var i = 0; i < size - 1; i++) { 
        for(var j = 0; j < size - i - 1; j++) { 
            if(values[j] >= values[j + 1]) {
                states[j] = 1; // << Highlight comparisons 
                states[j + 1] = 1; 
                if (step_button == true) {
                    // TODO: Swap only two elements
                } else if (step_button != true) {
                    await this.swap(values, j, j + 1);
                }
            } 
            states[j] = 2; 
        } 
        states[j] = 0; // << Sorted Order 
    } 
    sort_button = false; 
    return values; 
} 

I am trying to add a step feature for the following algorithm. When the step button is pressed I want one swap to be performed and the code following it to be executed. I have tried using a break and continue but this did not give me the result I was looking for. How can I simply swap two elements in the data set each time the button is pressed?


Solution

  • If I were you, I would copy the array and work on the copied version in the background and store a list of the swaps.

    and each time the button got presses I just get the top element for the list and swap the indices.

    Example: this 0-based array 3 1 2 the list of swaps will be 0 1 1 2

    So at the first button press, I would swap a[0] and a[1] at the second button press, I would swap a[1] and a[2]