
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check If Array Is Sorted Using Bubble Sort in Golang
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
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.
Advertisements