From 3f5ecc7fc2dd4508b10596aa6facf3e8a59b36fd Mon Sep 17 00:00:00 2001 From: Vishesh Jain <72205628+visheshj2005@users.noreply.github.com> Date: Tue, 7 Oct 2025 18:39:22 +0530 Subject: [PATCH] Add Bubble Sort implementation in bubblesort.go Implement Bubble Sort algorithm to sort an array of integers in ascending order. Includes user input for array size and elements. --- Golang/bubblesort.go | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Golang/bubblesort.go diff --git a/Golang/bubblesort.go b/Golang/bubblesort.go new file mode 100644 index 00000000..20d5111d --- /dev/null +++ b/Golang/bubblesort.go @@ -0,0 +1,46 @@ +// bubble_sort.go +// Run with: go run bubble_sort.go + +package main + +import ( + "fmt" +) + +// bubbleSort sorts the slice in ascending order using Bubble Sort algorithm. +func bubbleSort(arr []int) { + n := len(arr) + for i := 0; i < n-1; i++ { + swapped := false + for j := 0; j < n-i-1; j++ { + if arr[j] > arr[j+1] { + arr[j], arr[j+1] = arr[j+1], arr[j] // swap + swapped = true + } + } + // If no two elements were swapped in the inner loop, break early + if !swapped { + break + } + } +} + +func main() { + var n int + fmt.Print("Enter number of elements: ") + fmt.Scan(&n) + + arr := make([]int, n) + fmt.Println("Enter", n, "elements:") + for i := 0; i < n; i++ { + fmt.Scan(&arr[i]) + } + + bubbleSort(arr) + + fmt.Println("Sorted array:") + for _, v := range arr { + fmt.Print(v, " ") + } + fmt.Println() +}