# Write a Golang program to check whether a given array is sorted or not (Using Bubble Sort Technique)

Go ProgrammingServer Side ProgrammingProgramming

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

## Examples

• Input arr = [7, 15, 21, 26, 33] => Array is already sorted.
• Input arr = [7, 5, 1, 6, 3] => Array is not sorted.

## Approach to solve this problem

• Step 1: Iterate the array from the 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: If swap is not taking place in the first iteration, then print that “array is already sorted”.
• Step 4: If swap occurs, then print “array is not sorted”.

## Program

Live Demo

package main
import "fmt"
func checkSortedArray(arr []int){
sortedArray := true
for i:=0; i<=len(arr)-1; i++{
for j:=0; j<len(arr)-1-i; j++{
if arr[j]> arr[j+1]{
sortedArray = false
break
}
}
}
if sortedArray{
} else {
fmt.Println("Given array is not sorted.")
}
}

func main(){
checkSortedArray([]int{1, 3, 5, 6, 7, 8})
checkSortedArray([]int{1, 3, 5, 9, 4, 2})
checkSortedArray([]int{9, 7, 4, 2, 1, -1})
}

## Output

Given array is already sorted.
Given array is not sorted.
Given array is not sorted.
Updated on 04-Feb-2021 11:15:04