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


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{
      fmt.Println("Given array is already sorted.")
   } 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

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements