编写一个 Golang 程序来检查给定数组是否已排序(使用冒泡排序技术)
范例
- 输入 arr = [7, 15, 21, 26, 33] => 数组已排序。
- 输入 arr = [7, 5, 1, 6, 3] => 数组未排序。
解决此问题的步骤
- 步骤 1:迭代从第 0 个索引到 **n-1** 的数组。
- 步骤 2:迭代从第 0 个索引到 **n-1-i** 数组,其中 **i** 是上述循环的索引。
- 步骤 3:如果在第一次迭代中未进行交换,则打印“数组已排序”。
- 步骤 4:如果发生交换,则打印“数组未排序”。
程序
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})
}输出
Given array is already sorted. Given array is not sorted. Given array is not sorted.
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP