Improving the Performance of the Classic Bubble Sort Algorithm

May 16, 2022

 

Sorting algorithms are a crucial part of programming, and choosing the right one for your data is essential for optimal performance. However, even simple algorithms like Bubble Sort can be improved to handle larger datasets more efficiently. In this post, we’ll explore a few ways to optimize the classic Bubble Sort algorithm, using a PlayBASIC example to demonstrate the improvements.

Understanding Bubble Sort

Bubble Sort is one of the most commonly taught sorting algorithms in programming. It’s simple to understand but can be slow for large datasets. The concept is straightforward: you iterate through the data, comparing adjacent elements, and swap them if they are in the wrong order. The process repeats until no swaps are necessary, meaning the array is sorted.

The key flaw of Bubble Sort is that it’s an "n-squared" algorithm, meaning its performance degrades rapidly as the number of elements in the array increases. Despite this, there are still a few optimizations we can apply to make it faster in certain situations.

Optimizing Bubble Sort

While Bubble Sort will never be the fastest sorting algorithm, there are ways to make it more efficient for specific datasets. Below are a couple of key improvements that can help speed up the process.

1. Reduce the Set Size After Each Pass

One improvement involves reducing the size of the array that’s being processed after each pass. As each pass moves the largest remaining element to the end of the array, you don’t need to check it again in subsequent passes. By decreasing the range of elements to check after each pass, you can reduce unnecessary comparisons and speed up the sorting process.

2. Bi-directional Bubble Sort

Instead of only iterating left to right, the Bi-directional Bubble Sort (also known as Cocktail Shaker Sort) goes through the array in both directions. The first pass moves the largest element to the end of the array (just like the classic version), but the next pass moves the smallest element to the beginning of the array. By alternating directions, this approach can reduce the number of passes needed to sort the data.

Example Code in PlayBASIC

Here’s an example implementation of these optimizations in PlayBASIC, which demonstrates the classic Bubble Sort alongside the faster variants:


loadfont "Courier New", 1, 24

MaxItems = 500
DIM Table(MaxItems)
DIM Stats#(10, 5)

DO
    Cls

    inc frames
    Seed = Timer()

    Test = 1

    SeedTable(Seed, MaxItems)
    StartInterval(0)
    ClassicBubbleSort(MaxItems)
    tt1 +  = EndInterval(0)
    test = Results("Classic Bubble Sort:", Test, MaxItems, Tt1, Frames)



    SeedTable(Seed, MaxItems)
    StartInterval(0)
    ClassicBubbleSortFaster(MaxItems)
    tt2 +  = EndInterval(0)
    test = Results("Classic Bubble Sort Faster:", Test, MaxItems, TT2, Frames)


    SeedTable(Seed, MaxItems)
    StartInterval(0)
    BiDirectionalBubbleSort(MaxItems)
    tt3 +  = EndInterval(0)
    test = Results("BiDirectional Bubble Sort:", Test, MaxItems, Tt3, Frames)


    Sync

    REPEAT
    UNTIL enterkey() = 0

LOOP


FUNCTION ShowTable(items)

    t$ = ""
    n = 0
    FOR lp = 0 to items
        T$ = t$ + str$(table(lp)) + ", "
        inc n
        IF n > 10
            t$ = Left$(t$, Len(t$) - 1)
            print t$
            t$ = ""
            n = 0
        ENDIF

    NEXT lp

    IF t$ <  > "" THEN print Left$(t$, Len(t$) - 1)

ENDFUNCTION


FUNCTION SeedTable(Seed, Items)
    Randomize seed
    FOR lp = 0 to Items
        Table(lp) = Rnd(32000)
    NEXT lp
ENDFUNCTION


FUNCTION ValidateTable(Items)
    result = 0
    FOR lp = 0 to items - 1
        IF Table(lp) > Table(lp + 1)
            result = 1
            exit
        ENDIF
    NEXT lp
ENDFUNCTION Result



FUNCTION Results(Name$, index, Items, Time, Frames)
    ` Total Time
    Time = Time / 1000
    Stats#(index, 1) = Stats#(index, 1) + time

    print "Sort Type:" + name$
    print "Total Time:" + str$(Stats#(index, 1))
    print "Average Time:" + str$(Stats#(index, 1) / frames)

    IF ValidateTable(Items) = 0
        Print "Array Sorted"
        ELSE
        print "NOT SORTED - ERROR"
    ENDIF
    print ""

    inc index

ENDFUNCTION index




FUNCTION ClassicBubbleSort(Items)
    Flag = 0
    REPEAT
        Done = 0
        FOR lp = 0 to items - 1
            IF Table(lp) > Table(lp + 1)
                done = 1
                t = Table(lp)
                Table(lp) = Table(lp + 1)
                Table(lp + 1) = t
            ENDIF
        NEXT lp
    UNTIL done = 0
ENDFUNCTION



FUNCTION ClassicBubbleSortFaster(Items)
    Flag = 0
    REPEAT
        Done = 0
        dec items
        FOR lp = 0 to items
            IF Table(lp) > Table(lp + 1)
                done = 1
                t = Table(lp)
                Table(lp) = Table(lp + 1)
                Table(lp + 1) = t
            ENDIF
        NEXT lp
    UNTIL done = 0
ENDFUNCTION


FUNCTION BiDirectionalBubbleSort(Items)
    First = 0
    Last = Items

    REPEAT
        Done = 0
        dec Last
        FOR lp = First to Last
            V = Table(lp + 1)
            IF Table(lp) > V
                done = 1
                Table(lp + 1) = Table(lp)
                Table(lp) = v
            ENDIF
        NEXT lp

        IF Done = 1
            Done = 0
            inc First
            FOR lp = Last to First step - 1
                V = Table(lp - 1)
                IF V > Table(lp)
                    Done = 1
                    Table(lp - 1) = Table(lp)
                    Table(lp) = v
                ENDIF
            NEXT lp
        ENDIF
    UNTIL Done = 0
ENDFUNCTION

Explanation of the Code

  • Table Initialization: We start by defining an array (`Table`) and filling it with random numbers using the `SeedTable` function.
  • Sorting Functions: Three sorting functions are defined:
  • - `ClassicBubbleSort`: The traditional Bubble Sort that compares adjacent elements and swaps them.

    - `ClassicBubbleSortFaster`: This is an optimized version of the classic algorithm where we reduce the set size after each pass.

    - `BiDirectionalBubbleSort`: This method sorts the array by alternating the direction of passes, improving performance.

  • Performance Tracking: The sorting times are tracked using `StartInterval` and `EndInterval`, allowing us to compare the performance of each sorting method.
  • Results and Performance

    After running the sorting methods, we display the results, including the total time taken and the average time per frame. We also validate that the array is correctly sorted at the end of each method.

    The results can vary depending on the size of the dataset, but in most cases, the optimized versions of Bubble Sort will show significant performance improvements compared to the classic method.

    Final Thoughts

    While Bubble Sort is not the most efficient sorting algorithm, these optimizations provide a good demonstration of how you can improve its performance in certain scenarios. Reducing the size of the set and implementing bi-directional sorting can make the classic Bubble Sort more practical for moderate-sized datasets.

    However, if you’re dealing with larger datasets, it’s often better to use more advanced sorting algorithms like Merge Sort or Quick Sort, which offer much better performance.

    As always, the key takeaway is that sorting is situational, and selecting the right algorithm for your data is essential. These optimizations are not a silver bullet but can provide useful improvements in the right circumstances.

    Have Fun with Sorting!

    Sorting is a fundamental concept in computer science, and experimenting with different algorithms and optimizations can help you understand how they work. Feel free to try out these optimizations in your own projects and see how they perform with your data!

    Links:

  • PlayBASIC,com
  • Learn to basic game programming (on Amazon)
  • Learn to code for beginners (on Amazon)


  • G2D: Bringing OpenGL to PlayBASIC for Enhanced Rendering

    November 15, 2015

     

    G2D: Bringing OpenGL to PlayBASIC for Enhanced Rendering

    G2D is a promising alternative rendering library for PlayBASIC, offering an OpenGL-based solution for graphics rendering. While PlayBASIC traditionally uses DirectX and software rendering, G2D leverages the power of the OpenGL API to provide a more efficient and flexible rendering option. Although G2D is still in its early stages, the library has already shown significant potential in terms of compatibility and performance.

    What is G2D?

    At its core, G2D is a minimal rendering library built to work with PlayBASIC, a beginner-friendly programming language for game development. It replaces PlayBASIC’s default rendering system with OpenGL, offering a faster, more modern alternative for developers seeking improved graphical performance.

    Currently, G2D supports a basic set of commands, including primitives like lines, shapes, and images. These commands work similarly to their PlayBASIC counterparts, but all rendering happens on the OpenGL canvas, ensuring faster performance in windowed modes.

    It’s important to note that G2D is currently only compatible with PlayBASIC’s windowed modes, as it directly attaches the OpenGL viewport to the PlayBASIC window. To hide the default DirectX screen, you can use the `ScreenLayout` command to position it outside the window.

    Building Basic Image Support

    One of the first features G2D developers focused on was integrating basic image commands. The goal was to maintain compatibility with PlayBASIC’s internal image management system (AFX) while utilizing OpenGL for rendering. When an image is loaded into G2D, it’s first imported into PlayBASIC’s internal image slot and then converted into a texture that OpenGL can use. This dual approach allows developers to continue using PlayBASIC’s native sprite and collision functions while benefiting from the performance gains of OpenGL.

    Expanding Core Primitives

    In the early stages, G2D developers concentrated on expanding the core primitive commands for more complex scenes. One challenge was making sprites compatible with OpenGL’s efficient rendering pipeline. OpenGL, like Direct3D, performs best when rendering many polygons from a single texture to reduce overhead, but PlayBASIC’s sprites are handled differently.

    To solve this, G2D developers experimented with ways to efficiently render sprites while preserving PlayBASIC’s collision and vector-based interactions. One solution was creating a dedicated GL sprite layer that caches texture states, reducing texture swaps between polygons. This approach mitigates performance issues when sprites constantly switch textures.

    For maps, G2D introduced the `g2dDrawMap` function, which allows PlayBASIC maps to be rendered using OpenGL textures. This function takes parameters like texture index and map layout, enabling seamless integration with PlayBASIC’s map system while utilizing OpenGL for faster rendering.

    Optimizing Sprite Rendering with `g2dDrawAllSprites`

    After implementing basic image support, the G2D team moved on to optimizing sprite rendering. The `g2dDrawAllSprites` function was introduced to handle large numbers of sprites efficiently. It takes advantage of OpenGL’s ability to batch multiple sprite draw calls into a single operation, improving performance even with a high volume of sprites.

    In early tests, the `g2dDrawAllSprites` function was able to render 1000 anti-aliased sprites at 27 frames per second on a standard test machine without optimization. While impressive, G2D developers acknowledged the need for further optimizations to improve rendering speed.

    Dealing with Sprite Issues and Legacy Commands

    During development, the G2D team encountered challenges with legacy PlayBASIC sprite commands, particularly functions like `GetSpriteRect()` and `SpriteInRegion()`, which are critical for determining sprite visibility and bounding boxes in the OpenGL viewport. These functions were causing crashes and unexpected behavior, so the G2D team worked to fix them.

    The fixes involved rewriting portions of the code to ensure that the OpenGL-based wrapper functions interacted correctly with PlayBASIC’s internal sprite system. While some legacy functions, like sprite clipping, may still not work as expected, these issues are being addressed in ongoing updates.

    Introducing `g2dDrawOrderedSprite` for Scene Sorting

    To further optimize G2D, the team introduced the `g2dDrawOrderedSprite` function, which allows sprites to be sorted by depth values. This ensures that objects closer to the camera are rendered in front of objects that are farther away—essential for creating 2D scenes with proper layering and depth.

    The `g2dDrawOrderedSprite` function works similarly to PlayBASIC’s `DrawOrderedSprite` command, but with the added advantage of OpenGL’s GPU acceleration. This enhancement allows G2D to handle complex scenes more efficiently by offloading rendering to the GPU.

    Future Plans and Challenges

    Although G2D has made impressive strides, many features and improvements are still in the works. Future updates will focus on adding interfaces for more advanced features like maps, shapes, and fonts. The G2D team is also working to resolve performance issues related to texture sizes, particularly for fonts, which may cause problems if the texture exceeds the size limits of older graphics cards.

    For font rendering, the team plans to convert text into meshes and render them onto the OpenGL surface. While feasible, this approach requires attention to texture sizes, especially for large characters. As G2D continues to evolve, the goal is to make font rendering more flexible and optimized for a wide range of hardware configurations.

    Conclusion

    G2D is an exciting new rendering library for PlayBASIC that harnesses the power of OpenGL for faster and more efficient graphics rendering. Although still in the early stages, G2D already provides a solid foundation for developers looking to enhance the graphical performance of their PlayBASIC projects. With ongoing improvements and optimizations, G2D promises to be a valuable tool for PlayBASIC developers, offering more flexibility and control over rendering while maintaining compatibility with PlayBASIC’s internal systems.

    As G2D evolves, it has the potential to become a go-to solution for developers looking to push the limits of PlayBASIC and OpenGL, making it an exciting development to follow for anyone interested in 2D game programming with PlayBASIC.


    About the Author:

    Kevin Picone is the creator of PlayBASIC, a beginner-friendly programming language for creating 2D games, and the lead developer of the G2D particle library. With years of experience in both game development and programming tools, Kevin is passionate about making powerful game creation tools accessible to everyone, from beginner to advanced developers.


    Links:

  • G2D - 2D OpenGL library for PlayBASIC (WIP / BLOG / SCRATCH PAD)
  • PlayBASIC,com

  • Syntax Highlighting PlayBASIC Code Example

    August 03, 2012

     

    Vector Library

    This is simple library of 2d vector functions. Bellow is the example.

    	//  Use a typed array to hold all the vectors we'll be using
    	Dim vectors(100) as vector2d
    	for lp =0 to getArrayElements(vectors())
    		vectors(lp)= new vector2D
    	next
    
    
    	//  declare some pointers of type vector
    	// for use in the examples
    	Dim N as vector2d pointer
    	Dim V1 as vector2d pointer
    	Dim V2 as vector2d pointer
    	Dim OldPoint as vector2D pointer
    
    	//  Get pointers to some pre--alloated
    	//  vectors in our cache array
    	n = Vectors(0).vector2d
    	V1 = Vectors(1).vector2d
    	V2 = Vectors(2).vector2d
    
    
    	Dim CurrentPoint as vector2D pointer
    	CurrentPOint = Vectors(3).vector2d
    
    	Dim OldPoint as vector2D pointer
    	OldPOint = Vectors(4).vector2d
    
    	Dim Lerp1 as vector2D pointer
    	Lerp1 = Vectors(10).vector2d
    
    	Dim Lerp2 as vector2D pointer
    	Lerp2 = Vectors(11).vector2d
    
    
    	SetVector2d lerp1, 500,100
    	SetPolar2d lerp2, Rnd(36),rndrange(10,100)
    	Addvectors2d Lerp2, Lerp2, Lerp1
    
    
    
    	// Set up this vector
    	Setvector2d OldPOint,Mousex(),MouseY()
    	Flushmouse
    
    	// -----------------------------------------
    	Do
    	// -----------------------------------------
    
    		CLS
    
    
    		// Set up this vecor
    		Setvector2d CurrentPoint,Mousex(),MouseY()
    
    
    		circlec OldPoint.X,OldPoint.Y, 50,true, $00ff00
    
    		circle CurrentPoint.X,CurrentPOint.Y, 50,true
    
    
    		// Subtract target from current  N = Old - Current
    		Subvectors2d(N , oldPoint,CurrentPoint)
    
    		ypos= 50
    
    		text 10,Ypos, "Delta:"+StrVector2d$(N)
    
    		//  Get the length of this delta vector
    		Dist#=GetVectorLenght2D(N)
    
    		// normalize N = and store it back in N
    		GetVectorNormal2D(N , N)
    
    		text 10,Ypos+30, "Normalized:"+StrVector2d$(N)
    
    
    		//  Scale Normal by Dist#
    		Multvector2d(N , N, Dist#)
    
    		text 10,Ypos+60, "Scaled Normalized:"+StrVector2d$(N)
    
    		//  Add origin (current point) back on.
    		Addvectors2d(N , N, CurrentPoint)
    
    		text 10,Ypos+90, "Result:"+StrVector2d$(N)
    
    
    		//  Scale it  so we can draw line between them
    		line CurrentPOint.x,CurrentPOint.y,n.x,n.y
    
    		if Mousebutton()=1
    				CopyVector2d OldPoint,CurrentPOint
    		endif
    
    
    		//  test lerp
    		Linec Lerp1.x,Lerp1.y,Lerp2.x,Lerp2.y, $ff00ff
    
    		//
    		LerpFrame		=mod(LerpFrame+1,100)
    		LerpScale#		=LerpFrame/100.0
    
    		LerpVector2d N,Lerp1,Lerp2,LerpScale#
    
    		Circlec n.x , n.y, 5, true ,$ff00ff
    
    
    		//  Curve Lerp vector to the one between
    		LerpVector2d V1,Lerp1,Lerp2,LerpScale#
    		LerpVector2d V2,CurrentPoint,OldPoint,LerpScale#
    		LerpVector2d V1,V2,V1,LerpScale#
    		Circlec v1.x , v1.y, 5, true ,$ff00ff
    
    		LerpVector2d V1,Lerp1,Oldpoint,LerpScale#
    		LerpVector2d V2,lerp2,CurrentPoint,LerpScale#
    		LerpVector2d V1,V2,V1,LerpScale#
    		Circlec v1.x , v1.y, 5, true ,$ff00ff
    
    		Sync
    
    loop  Spacekey()