- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a Golang program to sort an array using Bubble Sort
Definition: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order.
Examples
Input arr = [7, 5, 1, 6, 3]
- 1st iteration => swap(7, 5) => swap(7, 1) => swap(7, 6) => swap(7, 3) => [5, 1, 6, 3, 7]
- 2nd iteration => [1, 5, 3, 6, 7]
- 3rd iteration => [1, 3, 5, 6, 7]
- 4th iteration => [1, 3, 5, 6, 7]
- 5th iteration => [1, 3, 5, 6, 7]
Approach to solve this problem
Step 1: Iterate the array from 0th index to n-1.
Step 2: Iterate the array from the 0th index to n-1-i, where i is the index of the above loop.
Step 3: Swap if the highest element is at the starting position of an array, else leave.
Step 3: At the end, return the array.
Time Complexity: O(n2)
Program
package main import "fmt" func bubbleSort(arr []int) []int{ for i:=0; i<=len(arr)-1; i++{ for j:=0; j<len(arr)-1-i; j++{ if arr[j]> arr[j+1]{ arr[j], arr[j+1] = arr[j+1], arr[j] } } } return arr }
Output
[0 1 2 5 6] [2 3 4 5 6] [1 2 3 4 5]
- Related Articles
- Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)
- Golang Program To Sort An Array In Ascending Order Using Insertion Sort
- Golang Program to sort an array in descending order using insertion sort
- Golang Program To Sort An Array
- 8085 Program to perform sorting using bubble sort
- Write a Golang program to sort a binary array in linear time
- C program to sort an array by using merge sort
- JavaScript Bubble sort for objects in an array
- Java program to implement bubble sort
- C++ Program to Implement Bubble Sort
- C program to sort a given list of numbers in ascending order using Bubble sort
- Python Program for Bubble Sort
- Bubble Sort program in C#
- 8085 program for bubble sort
- Bubble Sort

Advertisements