如何返回Counting Sort的排序索引?

时间:2017-03-11 18:10:35

标签: algorithm sorting counting-sort

我想从下面的Counting Sort算法返回x数组的排序索引,它必须简单但我无法弄清楚如何做到这一点!有人可以指导我如何在Matlab或Golang中做到这一点,或者下面的算法的任何idomatic c风格演示?非常感谢。

private void btnFolieSpeichern_Click(object sender, EventArgs e)
{
    try
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = "INSERT INTO Folien (Hersteller,Serie,Farbe,EK-Preis,Bild) VALUES ('" + tbFolieHersteller.Text + "','" + tbFolieSerie.Text + "','" + tbFolieFarbe.Text + "','" + tbFolieEKPreis.Text + "',@folienbild)";

        //converting photo to binary data
        if (pbFolieBildHinzufügen.Image != null)
        {
            MemoryStream ms = new MemoryStream();
            pbFolieBildHinzufügen.Image.Save(ms, ImageFormat.Jpeg);
            byte[] photo_aray = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo_aray, 0, photo_aray.Length);
            command.Parameters.AddWithValue("@folienbild", photo_aray);
        }

        command.ExecuteNonQuery();
        MessageBox.Show("Folie erfolgreich hinzugefügt!", "Erfolgreich!", MessageBoxButtons.OK, MessageBoxIcon.Information);
        connection.Close();

        tbFolieHersteller.Text = "";
        tbFolieSerie.Text = "";
        tbFolieFarbe.Text = "";
        tbFolieEKPreis.Text = "";
        pbFolieBildHinzufügen.Image = null;
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error " + ex);
    }
}

上面的代码返回sorted_x = [2 2 2 3 5 6] 但我想修改它也返回sorted_indices = [2 5 6 4 3 1]

由于

3 个答案:

答案 0 :(得分:0)

您可以使用map存储索引 -

package main
import "fmt"

func main(){
    nums := [6]int{6, 2, 5, 3, 2, 2}
    count := make(map[int][]int)
    for i, v := range nums {
        count[v] = append(count[v], i+1)
    }
    output := []int{}
    for i := 0; i < 10; i++ {
        output = append(output, count[i]...)
    }
    for i := 0; i < len(output); i++ {
        fmt.Printf("%d ", nums[output[i]-1])
    }
    fmt.Println()
    fmt.Println("The indices are:")
    fmt.Println(output)
}

输出 -

2 2 2 3 5 6 
The indices are:
[2 5 6 4 3 1]

答案 1 :(得分:0)

在matlab中,sort函数的第二个输出值是索引。试试这个:

[sorted, s_ind] = sort(x); 

答案 2 :(得分:0)

例如,使用Go sort包,

package main

import (
    "fmt"
    "sort"
)

type AX struct{ A, X []int }

func (ax AX) Len() int {
    return len(ax.A)
}
func (ax AX) Swap(i, j int) {
    ax.A[i], ax.A[j] = ax.A[j], ax.A[i]
    ax.X[i], ax.X[j] = ax.X[j], ax.X[i]
}
func (ax AX) Less(i, j int) bool {
    return ax.A[i] < ax.A[j]
}

func sortAX(a []int) (x []int) {
    x = make([]int, len(a))
    for i := range x {
        x[i] = i
    }
    sort.Stable(AX{A: a, X: x})
    return x
}

func main() {
    a := []int{6, 2, 5, 3, 2, 2}
    fmt.Println("a:", a)
    x := sortAX(a)
    fmt.Println("a:", a)
    fmt.Println("x:", x)
}

输出(Go指数从0开始):

a: [6 2 5 3 2 2]
a: [2 2 2 3 5 6]
x: [1 4 5 3 2 0]

参考文献:

Go: Package sort