Golang

 

Introduction

Sorting is a fundamental concept in computer science that refers to the process of arranging data in a specific order (ascending or descending). Efficient sorting algorithms are essential for optimizing performance in a variety of applications, from databases to search engines. This tutorial focuses on implementing and comparing three common sorting algorithms: Bubble Sort, Quick Sort, and Merge Sort. We will explore their working principles, advantages, and performance differences.

Objectives

  • Understand the basic concept of sorting algorithms.
  • Implement Bubble Sort, Quick Sort, and Merge Sort in Go programming language.
  • Compare the efficiency and behavior of each algorithm on sample datasets.

Go Program Implementation


package main

import (
    "fmt"
    "math/rand"
    "time"
)

// Bubble Sort Algorithm
func bubbleSort(arr []int) {
    n := len(arr)
    for i := 0; i < n-1; i++ {
        for j := 0; j < n-i-1; j++ { if arr[j] > arr[j+1] {
                arr[j], arr[j+1] = arr[j+1], arr[j]
            }
        }
    }
}

// Quick Sort Algorithm
func quickSort(arr []int) []int {
    if len(arr) < 2 {
        return arr
    }
    pivot := arr[0]
    left := []int{}
    right := []int{}
    for _, v := range arr[1:] {
        if v < pivot {
            left = append(left, v)
        } else {
            right = append(right, v)
        }
    }
    left = quickSort(left)
    right = quickSort(right)
    return append(append(left, pivot), right...)
}

// Merge Sort Algorithm
func mergeSort(arr []int) []int {
    if len(arr) <= 1 {
        return arr
    }
    mid := len(arr) / 2
    left := mergeSort(arr[:mid])
    right := mergeSort(arr[mid:])
    return merge(left, right)
}

func merge(left, right []int) []int {
    result := []int{}
    i, j := 0, 0
    for i < len(left) && j < len(right) {
        if left[i] < right[j] {
            result = append(result, left[i])
            i++
        } else {
            result = append(result, right[j])
            j++
        }
    }
    result = append(result, left[i:]...)
    result = append(result, right[j:]...)
    return result
}

// Function to generate random data
func generateRandomData(size int) []int {
    rand.Seed(time.Now().UnixNano())
    data := make([]int, size)
    for i := 0; i < size; i++ {
        data[i] = rand.Intn(1000)
    }
    return data
}

func main() {
    // Generate random data
    data := generateRandomData(10)
    fmt.Println("Original Data:", data)

    // Bubble Sort
    bubbleSorted := make([]int, len(data))
    copy(bubbleSorted, data)
    bubbleSort(bubbleSorted)
    fmt.Println("Bubble Sorted Data:", bubbleSorted)

    // Quick Sort
    quickSorted := quickSort(data)
    fmt.Println("Quick Sorted Data:", quickSorted)

    // Merge Sort
    mergeSorted := mergeSort(data)
    fmt.Println("Merge Sorted Data:", mergeSorted)
}
            

Explanation of the Program

This Go program demonstrates the implementation of three sorting algorithms: Bubble Sort, Quick Sort, and Merge Sort. Below is an explanation of each component:

  • Bubble Sort: It repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. This process is repeated until the list is sorted.
  • Quick Sort: It selects a “pivot” element and partitions the array around the pivot, recursively sorting the subarrays.
  • Merge Sort: It divides the array into two halves, recursively sorts each half, and merges the sorted halves into a single sorted array.

The generateRandomData function is used to create an array of random integers for testing the sorting algorithms. The main function first displays the unsorted data, then sorts the data using each algorithm and prints the sorted results.

How to Run the Program

Follow these steps to run the program:

  1. Install Go programming language from the official website (https://golang.org/).
  2. Save the above program as sorting.go on your system.
  3. Open a terminal or command prompt and navigate to the directory where you saved the sorting.go file.
  4. Run the program using the command: go run sorting.go
  5. The output will display the original, bubble sorted, quick sorted, and merge sorted data.
© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)