DEV Community

Cover image for Mastering Algorithms with Go: A Beginner's Guide to Sorting Small Data Sets 🔥
Allan Githaiga
Allan Githaiga

Posted on

Mastering Algorithms with Go: A Beginner's Guide to Sorting Small Data Sets 🔥

algorithims
Algorithms are the backbone of problem-solving in programming. Whether you're organizing your tasks, finding the fastest route on a map, or simply sorting a list of names, algorithms come into play. In the world of software development, understanding algorithms is crucial for writing efficient, scalable, and maintainable code.

In this article, we'll focus on one of the most basic & fundamental algorithmic challenges—sorting small data sets. We'll explore how to implement sorting algorithms in Go and understand their relevance in real-life scenarios.

algorithims1

Why This Topic Matters

Sorting data is one of the most common tasks developers face. From ranking search results to organizing user data, efficient sorting can dramatically impact application performance. For beginners, learning sorting algorithms provides a strong foundation for understanding more complex algorithmic concepts.

But here's a twist: What if you’re faced with a situation where performance matters even for small data sets? Imagine you're developing a leaderboard for a local hackathon where rankings must update in real-time. You need a sorting solution that's both simple and efficient. That’s where this article comes in.

1. QuickSort Algorithm

The following code implements a dynamic leaderboard for a local hackathon. It uses efficient sorting and other utility functions to handle real-time updates.

// QuickSort sorts the participants slice in descending order of scores.
// It uses a divide-and-conquer approach for efficient sorting.
func QuickSort(participants []models.Participant, low, high int) {
    if low < high {
        // Find the pivot position
        p := partition(participants, low, high)
        // Recursively sort the left and right subarrays
        QuickSort(participants, low, p-1)
        QuickSort(participants, p+1, high)
    }
}

Enter fullscreen mode Exit fullscreen mode

Input: The slice of participants, along with low and high indices for the current sorting range.
Output: The slice is sorted in descending order.
How it works:

  1. Calls the partition function to position one element (pivot) in its correct sorted place.
  2. Recursively sorts the two halves of the array around the pivot.

2. Partition Function

// partition rearranges the slice such that elements greater than or equal to the pivot
// appear before it, and elements less than the pivot come after it.
func partition(participants []models.Participant, low, high int) int {
    pivot := participants[high].Score // Select the pivot as the last element
    i := low - 1                      // Initialize pointer for greater elements

    for j := low; j < high; j++ {
        // If the current element's score is greater than or equal to the pivot
        if participants[j].Score >= pivot {
            i++ // Move the pointer
            // Swap the current element with the element at pointer i
            participants[i], participants[j] = participants[j], participants[i]
        }
    }

    // Finally, place the pivot in its correct position
    participants[i+1], participants[high] = participants[high], participants[i+1]
    return i + 1 // Return the index of the pivot
}

Enter fullscreen mode Exit fullscreen mode

This function ensures elements are rearranged:

  • Larger scores are placed on the left of the pivot.
  • Smaller scores are placed on the right.

Returns the pivot index, which divides the array for further sorting.

3. Update Scores

// UpdateScore updates a participant's score based on their name.
// If the participant isn't found, it displays a message.
func UpdateScore(participants []models.Participant, name string, newScore int) {
    for i := range participants {
        // Find the participant by name
        if participants[i].Name == name {
            // Update their score
            participants[i].Score = newScore
            return
        }
    }
    fmt.Println("Participant not found!")
}

Enter fullscreen mode Exit fullscreen mode

Purpose: Quickly updates a participant’s score.
Flow:

  • Loops through the participants slice. If a match is found (Name == name), updates their Score.
  • If no match is found, prints a helpful message.

4. Display the Leaderboard

// DisplayLeaderboard prints the participants in sorted order.
func DisplayLeaderboard(participants []models.Participant) {
    fmt.Println("\n--- Hackathon Leaderboard ---")
    for i, participant := range participants {
        // Print each participant's rank, name, and score
        fmt.Printf("%d. %s - %d\n", i+1, participant.Name, participant.Score)
    }
}

Enter fullscreen mode Exit fullscreen mode

Purpose: Outputs the current state of the leaderboard.
How it works:

  • Iterates through the sorted slice.
  • Prints the rank, participant name, and score in a readable format.

5. Add a New Participant

// AddParticipant adds a new participant if their name isn't already present.
func AddParticipant(participants []models.Participant, name string, score int) ([]models.Participant, error) {
    // Check if the participant already exists
    if CheckIfParticipantExists(participants, name) {
        return participants, fmt.Errorf("participant with name %s already exists", name)
    }
    // Append the new participant
    participants = append(participants, models.Participant{Name: name, Score: score})
    return participants, nil
}

Enter fullscreen mode Exit fullscreen mode
  • Ensures no duplicate names in the leaderboard.
  • If the participant doesn’t already exist, appends them to the slice and returns the updated slice.

6. Check if a Participant Exists

// CheckIfParticipantExists checks if a participant with a given name exists in the slice.
func CheckIfParticipantExists(participants []models.Participant, name string) bool {
    for _, p := range participants {
        if p.Name == name {
            return true
        }
    }
    return false
}

Enter fullscreen mode Exit fullscreen mode
  • A helper function to verify if a participant’s name is already in the leaderboard.

7. sample workflow in Main

func main() {
    // Initialize participants
    participants := []models.Participant{
        {Name:"Alice",Score: 85},
        {Name:"Bob",Score: 70},
        {Name:"Charlie",Score: 90},
    }

    // Add a new participant
    participants, _ = AddParticipant(participants, "Diana", 75)

    // Update Bob's score
    UpdateScore(participants, "Bob", 95)

    // Sort the leaderboard
    QuickSort(participants, 0, len(participants)-1)

    // Display the leaderboard
    DisplayLeaderboard(participants)
}

Enter fullscreen mode Exit fullscreen mode

If you'd like to explore the complete code implementation and try it out for yourself, you can find the project on my GitHub repository Dynamic-Leaderboard. Feel free to clone it and experiment with the algorithms!
Happy coding 🎉

Top comments (0)