30 Ekim 2016 Pazar

Go'da sıralama işlemleri

Go programlama dilinde bir obje dizisini sıralayabilmek için sort.Interface kullanılabilir. Bu interface 3 basit metoda ihtiyaç duyar: Len, Less ve Swap


// dizideki eleman sayısını döner
Len() int
// Dizideki iki elemanı karşılaştırır. Burada karşılaştırma için // özel kod yazılır
Less(i, j int) bool
// i ve j indekslerindeki elemanların yerini değiştirir
Swap(i, j int)`

Aşağıdaki gibi bir struct tipinde elemanlar içeren bir dizi olsun.

type AboutMe struct {
       Id          int
       Name        string
       Description string
}

type AboutMeList []AboutMe

Aşağıdaki gibi bir fonksiyon ile test için geçici olarak aşağıdaki gibi data listesi oluşturulabilir.

func prepareTestData() AboutMeList {
       aboutList := make([]AboutMe, 0)
       about1 := AboutMe{}
       about1.Id = 3
       about1.Name = "Ali"
       about1.Description = "test1"
       about2 := AboutMe{}
       about2.Id = 3
       about2.Name = "Veli"
       about2.Description = "test2"
       about3 := AboutMe{}
       about3.Id = 1
       about3.Name = "Ahmet"
       about3.Description = "test3"
       about4 := AboutMe{}
       about4.Id = 4
       about4.Name = "Mehmet"
       about4.Description = "test4"
       aboutList = append(aboutList, about1)
       aboutList = append(aboutList, about2)
       aboutList = append(aboutList, about3)
       aboutList = append(aboutList, about4)
       return aboutList
}

Dizideki elemanlar id’ye göre sıralansın. Bunun için Len, Less ve Swap metotları aşağıdaki gibi düzenlenebilir:


func (aboutMe AboutMeList) Len() int {
       return len(aboutMe)
}

func (aboutMe AboutMeList) Less(i, j int) bool {
       return aboutMe[i].Id < aboutMe[j].Id
}

func (aboutMe AboutMeList) Swap(i, j int) {
       aboutMe[i], aboutMe[j] = aboutMe[j], aboutMe[i]
}

Servis çağrıldığında çalışacak handler metodu da aşağıdaki gibi yazılabilir:

func sortHandler(w http.ResponseWriter, r *http.Request) {
       about := prepareTestData()
       sort.Sort(about)
       b, err := json.Marshal(about)
       if (err != nil) {
              panic(err)
       }
       w.Write(b)
}

Main metodu:
func main() {
       http.HandleFunc("/sort", sortHandler)
       http.ListenAndServe(":8080", nil)
}


golang sort


Eğer birden fazla değere göre sıralama yapılmak istenirse, örneğin önce id sonra name gibi, Less fonksiyonu aşağıdaki gibi düzenlenebilir:

func (aboutMe AboutMeList) Less(i, j int) bool {
       if (aboutMe[i].Id < aboutMe[j].Id) {
              return true;
       }
       if (aboutMe[i].Id > aboutMe[j].Id) {
              return false;
       }
       return aboutMe[i].Name < aboutMe[j].Name
}

Hiç yorum yok :

Yorum Gönder