如何对数组进行排序

huangapple go评论85阅读模式
英文:

How to sort an array

问题

我有一个在Go语言中对数组进行排序的问题,这是我的代码:

func main() {
    fmt.Print("Masukkan Jumlah Data yang akan dimasukkan: ")
    var jumlahdata int
    fmt.Scanln(&jumlahdata)
    var DataDiagram = make([]int, jumlahdata)
    fmt.Print("Masukkan data secara berurutan dengan spasi sebagai pemisah antar angka: ")
    for i := 0; i < jumlahdata; i++ {
        fmt.Scanf("%d", &DataDiagram[i])
    }
    fmt.Print("\n")
    var max int = DataDiagram[0]
    for _, value := range DataDiagram { // Menemukan nilai maximum
        if value > max {
            max = value
        }
    }
    var mem int
    Sorting(DataDiagram, jumlahdata, mem, max)
}

func Grafik(jumlahdata int, max int, DataDiagram []int) {
    for i := max; i >= 1; i-- {    // membuat Data Diagram
        for j := 0; j < jumlahdata; j++ {
            if DataDiagram[j] >= i {
                fmt.Print(" | ")
            } else {
                fmt.Print("   ")
            }
        }
        fmt.Print("\n")
    }
    for i := 0; i < jumlahdata; i++ {
        fmt.Print("---")
    }
    fmt.Print("\n")
    fmt.Print(" ")
    for i := 0; i < jumlahdata; i++ {
        fmt.Print(DataDiagram[i], "  ")
    }
}

func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
    for langkah := 0; langkah < (jumlahdata-1) ; langkah++ {
        Grafik(jumlahdata, max, DataDiagram)
        for i := 0; i < jumlahdata - (langkah-1); i++ {
            if DataDiagram[i] > DataDiagram[i + 1] {
                mem := DataDiagram[i];
                DataDiagram[i] = DataDiagram[i + 1]
                DataDiagram[i + 1] = mem;
            }
        }
    }
}

我期望的输出应该是这样的:期望的输出

但实际输出却不是这样的,它给了我一个错误:给出的错误

有人可以给我一些指导如何解决这个问题吗?我昨天刚开始学Go语言,它和C语言相似,但一直给我越界错误。

英文:

I have problem for sorting my array in Go,
Here is my code :

func main() {
	fmt.Print(&quot;Masukkan Jumlah Data yang akan dimasukkan: &quot;)
	var jumlahdata int
	fmt.Scanln(&amp;jumlahdata)
	var DataDiagram = make([]int, jumlahdata)
	fmt.Print(&quot;Masukkan data secara berurutan dengan spasi sebagai pemisah antar angka: &quot;)
	for i := 0; i &lt; jumlahdata; i++ {
		fmt.Scanf(&quot;%d&quot;, &amp;DataDiagram[i])
	}
	fmt.Print(&quot;\n&quot;)
	var max int = DataDiagram[0]
	for _, value := range DataDiagram { // Menemukan nilai maximum
		if value &gt; max {
			max = value
		}
	}
	var mem int
	Sorting(DataDiagram, jumlahdata, mem, max)
}
func Grafik(jumlahdata int, max int, DataDiagram []int) {
	for i := max; i &gt;= 1; i-- {	// membuat Data Diagram
		for j := 0; j &lt; jumlahdata; j++ {
			if DataDiagram[j] &gt;= i {
				fmt.Print(&quot; | &quot;)
			} else {
				fmt.Print(&quot;   &quot;)
			}
		}
		fmt.Print(&quot;\n&quot;)
	}
	for i := 0; i &lt; jumlahdata; i++ {
		fmt.Print(&quot;---&quot;)
	}
	fmt.Print(&quot;\n&quot;)
	fmt.Print(&quot; &quot;)
	for i := 0; i &lt; jumlahdata; i++ {
		fmt.Print(DataDiagram[i], &quot;  &quot;)
	}
}
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
	for langkah := 0; langkah &lt; (jumlahdata-1) ; langkah++ {
		Grafik(jumlahdata, max, DataDiagram)
		for i := 0; i &lt; jumlahdata - (langkah-1); i++ {
			if DataDiagram[i] &gt; DataDiagram[i + 1] {
				mem := DataDiagram[i];
				DataDiagram[i] = DataDiagram[i + 1]
				DataDiagram[i + 1] = mem;
			}
		}
	}
}

What i expect is look like this:
What I Expect

But the output said otherwise, it give me error : It give me error

Can someone give some guide how to fix this 如何对数组进行排序 i just learn Go yesterday, it similiar to C, but keep giving me index out of range error

答案1

得分: 1

我了解你的任务是对一个整数数组进行排序,并将每一步的工作显示为图表。由于你必须展示你的工作过程,所以不能使用Go语言内置的排序函数,比如sort.Ints(DataDiagram)

你的问题出在Sorting函数上。

步骤1 你目前遇到的问题是,i最终会迭代到大于DataDiagram的上限索引。我们可以在下面的注释行中修复这个问题。

// 步骤1:修复迭代器
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
    for langkah := 0; langkah < (jumlahdata-1) ; langkah++ {
        Grafik(jumlahdata, max, DataDiagram)
        for i := 0; i < jumlahdata - 1; i++ { // 修改为:for i := 0; i < jumlahdata - (langkah-1); i++ {
            if DataDiagram[i] > DataDiagram[i + 1] {
                mem := DataDiagram[i];
                DataDiagram[i] = DataDiagram[i + 1]
                DataDiagram[i + 1] = mem;
            }
        }
    }
}

步骤2 代码不再崩溃,但不能保证排序,因为它只对输入进行了一次遍历。我们需要继续循环,直到不再发生交换。下面修复了这个问题。该代码现在在playground上产生了预期的输出。

// 步骤2:循环直到排序完成
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
    swapped := true

	for swapped {
        Grafik(jumlahdata, max, DataDiagram)
        swapped = false
        for i := 0; i < jumlahdata - 1; i++ {
            if DataDiagram[i] > DataDiagram[i + 1] {
                mem := DataDiagram[i];
                DataDiagram[i] = DataDiagram[i + 1]
                DataDiagram[i + 1] = mem;
                swapped = true
            }
        }
    }
}

步骤3 上述代码运行良好,但可能需要进行一些整理。最终结果在playground上没有改变。

// 步骤3:使代码更整洁
func Sorting(data []int) {

	max := data[0]

	for _, value := range data { // 找到最大值
		if value > max {
			max = value
		}
	}

	swapped := true

	for swapped {
		Grafik(len(data), max, data)
		swapped = false
		for i := 0; i < len(data)-1; i++ {
			if data[i] > data[i+1] {
				data[i], data[i+1] = data[i+1], data[i]
				swapped = true
			}
		}
	}
}
英文:

I understand your task is to sort an int "array" (slice, in go-speak), showing each step of your work as a graph. Because you must show your work, you can't use go's built-in sorting, e.g. sort.Ints(DataDiagram).

Your problems are with the Sorting function.

Step 1 Your immediate crash-causing problem is that i eventually iterates to a number larger than upper index of DataDiagram. That we fix in the commented line below.

// Step 1: fix the iterator
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
    for langkah := 0; langkah &lt; (jumlahdata-1) ; langkah++ {
        Grafik(jumlahdata, max, DataDiagram)
        for i := 0; i &lt; jumlahdata - 1; i++ { // Was: for i := 0; i &lt; jumlahdata - (langkah-1); i++ {
            if DataDiagram[i] &gt; DataDiagram[i + 1] {
                mem := DataDiagram[i];
                DataDiagram[i] = DataDiagram[i + 1]
                DataDiagram[i + 1] = mem;
            }
        }
    }
}

Step 2 The code no longer crashes, but is not guaranteed to sort, because it makes only one pass through the inputs. We need to continue looping until there's no more swapping taking place. That problem is fixed below. The code now produces the expected output on the playground.

// Step 2: loop until sorted
func Sorting(DataDiagram []int, jumlahdata int, mem int, max int) {
    swapped := true

	for swapped {
        Grafik(jumlahdata, max, DataDiagram)
        swapped = false
        for i := 0; i &lt; jumlahdata - 1; i++ {
            if DataDiagram[i] &gt; DataDiagram[i + 1] {
                mem := DataDiagram[i];
                DataDiagram[i] = DataDiagram[i + 1]
                DataDiagram[i + 1] = mem;
                swapped = true
            }
        }
    }
}

Step 3 The above code works fine, but perhaps can use some tidying. The end result is unchanged on the playground.

// Step 3: make it prettier
func Sorting(data []int) {

	max := data[0]

	for _, value := range data { // Menemukan nilai maximum
		if value &gt; max {
			max = value
		}
	}

	swapped := true

	for swapped {
		Grafik(len(data), max, data)
		swapped = false
		for i := 0; i &lt; len(data)-1; i++ {
			if data[i] &gt; data[i+1] {
				data[i], data[i+1] = data[i+1], data[i]
				swapped = true
			}
		}
	}
}

答案2

得分: 0

如果你只是使用sort.Ints(ints),会简单得多,你可以在这里看到示例:https://goplay.space/#i9VIrDG-vL-

英文:

It's much simpler if you would just use
sort.Ints(ints), which you can see here:
https://goplay.space/#i9VIrDG-vL-

huangapple
  • 本文由 发表于 2021年10月27日 09:48:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/69731818.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定